Ruby:仅反转字符串的前100个字符

时间:2015-01-22 21:42:13

标签: ruby string reverse upcase

我正在尝试对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

我确信有一种方法可以让这很容易,我只是没有发现优雅的解决方案。非常感谢任何帮助!

2 个答案:

答案 0 :(得分: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 

答案 1 :(得分:0)

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

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