Gsub doesn't work in the whole code snippet

Using this sample code

#!/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 result will be "tyampion zylophone excellent", not "tjampion zylophone exksellent"

The same applies if gsub is applied in each of them to separate words. I do not understand why he acts at the beginning, but not at the end.

Edit

The second case is a separate question 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
+3
source share
4 answers

When you first use gsub, you assign it to the paragrah parameter

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

The second time you miss an appointment

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

paragraph = paragraph.gsub("x","ks")
+4
source
paragraph.gsub!("x","ks")
puts paragraph

Or use RegExp (one line may work):

paragraph = "champion xylophone excellent"
paragraph = paragraph.gsub("ch","tj").gsub(/([\A\s])x(\w*)/){$1 + 'z'+ $2}.gsub("x","ks")

puts paragraph
+2
source

. , ; , ( ). ; map, . , , .

paragraph = "champion xylophone excellent"
words = paragraph.split(' ').map do |word|
  word.gsub('ch','tj') #new string
  word[0.1] = "z" if word.start_with?('x') #modified string
  word.gsub!('x','ks') #modified string
end
puts words.join(' ')
+2
source

If you want yours to gsubbe destructive, i.e. to change the value of the variable to which it was called, use gsub!. So:

paragraph.gsub!('ch', 'tj')

but not:

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

This is more eloquent, and Ruby developers recognize bang (!) Methods as destructive. And in your case you need a method gsub!instead of both callsgsub

0
source

All Articles