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

Ruby:只反转字符串的前100个字符,ruby,string,reverse,upcase,Ruby,String,Reverse,Upcase,我试图在Ruby中对字符串进行一些字符串操作。目标是在不影响字符串其余部分的情况下,仅对前100个字符进行剥离、反转、压缩和升格 这是我们将使用的字符串。行号是字符串的一部分。在赋值中,该字符串称为“字符串” 1. this string has leading space and too "MANY tabs and sPaCes betweenX" 2. thE indiVidual Words in each Line.X 3. eacH Line

我试图在Ruby中对字符串进行一些字符串操作。目标是在不影响字符串其余部分的情况下,仅对前100个字符进行剥离、反转、压缩和升格

这是我们将使用的字符串。行号是字符串的一部分。在赋值中,该字符串称为“字符串”

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

我确信有一种方法可以使这变得容易,我只是还没有找到优雅的解决方案。非常感谢您的帮助

您可以通过给出一个范围来替换字符串中的子字符串:

[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 

我已通过以下途径回答了我的问题:

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

谢谢你的回答!我发现你的解决方案和我的解决方案都有效,你的更干净。请注意,在这一行中,
压缩
不仅会删除顺序空格,还会删除字母(
“moon”。压缩#=>“mon”
)。如果只希望压缩空格,则需要
.squence(“”
)。资料来源: