0

我正在尝试对 Ruby 中的字符串进行一些字符串操作。目标是仅剥离、反转、压缩和大写前 100 个字符,而不影响字符串的其余部分。

这是我们将使用的字符串。行号是字符串的一部分。在分配中,这个字符串被称为“the_string”。

1.               this string has leading space and too    "MANY tabs and sPaCes betweenX"
2.   thE indiVidual Words in each Line.X
3.  eacH Line ends with a accidentally  aDDED   X.X
4.            in this lab you wilL WRITE code that "sAnITizES" this string by normalizingX
5.   ("nOrMaLiZiNg" means   capitalizing sentences   and setting otherX
6.  characterS to lower case)     and removes         the extra spaces between WOrds.X

这是我的工作:

puts the_string[0,100].strip.squeeze.reverse.upcase 

和输出:

I EHT .2
"XNEWTEB SECAPS DNA SBAT YNAM" OT DNA ECAPS GNIDAEL SAH GNIRTS SIHT .1

这是按照我想要的方式工作的,除了从字符串中删除剩余的字符(100 之后),我希望它们保持原位并且不变。此外,我不应该修改 object_id,因此我无法创建新字符串来解决此问题。我寻求的输出是:

I EHT .2
"XNEEWTEB SECAPS DNA SBAT YNAM" OOT DNA ECAPS GNIDAEL SAH GNIRTS SIHT .1ndiVidual Words in each Line.X
3.  eacH Line ends with a accidentally  aDDED   X.X
4.            in this lab you wilL WRITE code that "sAnITizES" this string by normalizingX
5.   ("nOrMaLiZiNg" means   capitalizing sentences   and setting otherX
6.  characterS to lower case)     and removes         the extra spaces between WOrds.X

我确信有一种方法可以让这变得简单,我只是还没有找到优雅的解决方案。任何帮助是极大的赞赏!

4

2 回答 2

2

您可以通过给出 Range 来替换字符串中的子字符串:

[1] pry(main)> string = "1234567890"
=> "1234567890"
[2] pry(main)> string.object_id
=> 70248091185880
[3] pry(main)> string[0...5]="abcde"
=> "abcde"
[4] pry(main)> string
=> "abcde67890"
[5] pry(main)> string.object_id
=> 70248091185880

因此,您的代码如下所示:

the_string[0...100] = the_string[0,100].strip.squeeze.reverse.upcase 
于 2015-01-22T21:46:27.727 回答
0

我已经通过以下方式回答了我的问题:

substring = the_string[0,100].strip.squeeze.reverse.upcase 
the_string[0,100] = substring
puts the_string
于 2015-01-22T21:51:04.120 回答