I'm reading a book on Ruby, and I just started a little while ago. I have gotten some decent ground and they just introduced Regular Expressions, but for some reason I can't get them to work. Take this code for example:
line = "Perl"
line.sub(/Perl/, 'Ruby')
puts line
When I run the code I still see "Perl" getting printed to the string when it should have replaced it with "Ruby". Also, when I do stuff like:
line = "Yes I like Ruby"
if line =~ /Ruby/
puts line
end
Instead of printing the index of where the expression starts (like the book says) it just prints out the string again.
Am I doing something wrong?
Cheers,
~ Alias
Moved to the brand new "Ruby Programming" forum :)
Hi!
2 solutions:
line = "Perl"
newline = line.sub(/Perl/, "Ruby")
# or
line.sub!(/Perl/, "Ruby")
line.sub() does not change the original line, line.sub! does.
This is very common in Ruby, other examples are
chomp --- chomp!
chop --- chop!
strip --- strip!
...