Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

gsub not working throughout code snippet

Tags:

ruby

gsub

Using this code example

#!/usr/bin/ruby
paragraph = "champion xylophone excellent"
paragraph = paragraph.gsub("ch","tj")
words = paragraph.split(/ /)
words.each do |word|
   if word[0,1] == "x"
     word[0.1] = "z" 
   end
end
paragraph = words.join(" ")
paragraph.gsub("x","ks")
print paragraph

The output will be 'tjampion zylophone excellent' rather than 'tjampion zylophone ekscellent'

The same applies if the gsub is applied within the each to the individual words. I don't understand why it acts at the beginning but not at the end.

Edit

Second case is a distinct issue from the first:

#!/usr/bin/ruby
paragraph = "champion xylophone excellent"
paragraph = paragraph.gsub("ch","tj")
words = paragraph.split(/ /)
words.each do |word|
   if word[0,1] == "x"
     word[0.1] = "z" 
   end
   word = word.gsub("x","ks")
end
paragraph = words.join(" ")
print paragraph
like image 563
jaz9090 Avatar asked Apr 24 '26 03:04

jaz9090


1 Answers

When you first use gsub you are assigning it to paragrah

paragraph = paragraph.gsub("ch","tj")

The second time you are missing the assignment

change paragraph.gsub("x","ks") to

paragraph = paragraph.gsub("x","ks")
like image 57
frostmatthew Avatar answered Apr 27 '26 05:04

frostmatthew



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!