使用此代码示例
#!/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
输出将是“tjampion zylophoneexcel”而不是“tjampion zylophone ekscellent”
如果在 each 中将 gsub 应用于单个单词,则同样适用。我不明白为什么它在开始时起作用,但在结束时却没有。
编辑
第二种情况与第一种情况不同:
#!/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