0

I'm trying to do some string manipulation on a string in Ruby. The goal is to strip, reverse, squeeze and upcase only the first 100 characters without affecting the rest of the string.

Here is the string we will work with. The line numbers are part of the string. In the assignment this string is referred to as '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

Here's what I've got working:

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

and the output:

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

This is working the way I want it to, except rather than remove the remaining characters from the string (after 100), I want them to remain in place, and unaltered. Additionally, I'm not supposed to modify the object_id, and so therefore I cannot create a new string to solve this problem. The output I seek is:

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

I am certain that there is a method that makes this easy, I just haven't discovered the elegant solution. Any help is greatly appreciated!

amoeboar
  • 355
  • 1
  • 4
  • 22

2 Answers2

2

You can replace the substring in a string by giving a 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

So, you code would look like:

the_string[0...100] = the_string[0,100].strip.squeeze.reverse.upcase 
Grych
  • 2,861
  • 13
  • 22
  • thank you for the answer! i've found that your solution and mine both work, with yours being cleaner. – amoeboar Jan 22 '15 at 21:54
  • Do note that `squeeze` in this one-liner will not only remove sequential spaces, but also letters as well (`"moon".squeeze #=> "mon"`). You want `.squeeze(" ")` if you only wish to squeeze the spaces. Source: http://apidock.com/ruby/String/squeeze – DRobinson Jan 22 '15 at 21:59
0

I have answered my question via:

substring = the_string[0,100].strip.squeeze.reverse.upcase 
the_string[0,100] = substring
puts the_string
amoeboar
  • 355
  • 1
  • 4
  • 22