使用此代码示例

#!/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 zylophone 优秀”而不是“tjampion zylophone ekscellent”

如果 gsub 在 each 内应用于单个单词,则同样适用。我不明白为什么它在开始时起作用而不是在结束时起作用。

编辑

第二种情况与第一种情况不同:
#!/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

最佳答案

当您第一次使用 gsub 时,您将其分配给段落

paragraph = paragraph.gsub("ch","tj")
第二次错过作业
paragraph.gsub("x","ks") 更改为
paragraph = paragraph.gsub("x","ks")

关于ruby - gsub 在整个代码片段中不起作用,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/10141833/

10-12 18:57