Ruby 使用gsub时如何限制替换的数量?

Ruby 使用gsub时如何限制替换的数量?,ruby,gsub,Ruby,Gsub,如何限制Ruby中字符串#gsub的替换次数 在PHP中,使用preg_replace很容易做到这一点,它使用一个参数来限制替换,但我不知道如何在Ruby中做到这一点。gsub替换所有发生的事件 你可以试试String#sub 您可以在gsub循环中创建计数器和减量 str = 'aaaaaaaaaa' count = 5 p str.gsub(/a/){if count.zero? then $& else count -= 1; 'x' end} # => "xxxxxaaaa

如何限制Ruby中字符串#gsub的替换次数


在PHP中,使用preg_replace很容易做到这一点,它使用一个参数来限制替换,但我不知道如何在Ruby中做到这一点。

gsub替换所有发生的事件

你可以试试String#sub


您可以在gsub循环中创建计数器和减量

str = 'aaaaaaaaaa'
count = 5
p str.gsub(/a/){if count.zero? then $& else count -= 1; 'x' end}
# => "xxxxxaaaaa"

该死我查看了字符串函数以找到gsub之外的其他内容,为什么我没有注意到sub!?谢谢工作,但它是丑陋的。难道没有更好的办法吗?我明白了。这是更好的。但是,当替换字符串与正则表达式匹配时,例如,
sub('a','cat')
,您需要修改正则表达式,例如,
sub(/\Ga/,'cat')
。或者,这是正确的吗?实际上,
\G
似乎不适用于
sub
。它每次都会重置。
str = 'aaaaaaaaaa'
# The following is so that the variable new_string exists in this scope, 
# not just within the block
new_string = str 
5.times do 
  new_string = new_string.sub('a', 'x')
end