3

使用此代码示例

#!/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
4

4 回答 4

5

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

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

第二次错过作业

更改paragraph.gsub("x","ks")

paragraph = paragraph.gsub("x","ks")
于 2012-04-13T13:35:44.507 回答
2

您的代码意外运行。工作部分使用修改字符串的字符串方法;不工作的部分使用产生新字符串(被丢弃)的方法。这令人困惑;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(' ')
于 2012-04-13T14:14:04.333 回答
2
paragraph.gsub!("x","ks")
puts paragraph

或者使用正则表达式(一行操作可以完成所有操作):

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

puts paragraph
于 2012-04-13T13:44:55.080 回答
0

If you want your gsub to be destructive, i.e. to change the value of the variable on which it was called, use gsub!. so:

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

rather than:

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

It's more concise, and Ruby developers recognize bang (!) methods as destructive. And in your case, you need the gsub! method in place of both calls to gsub

于 2012-04-13T13:40:54.660 回答