Ruby で String#gsub によって行われる置換の数をどのように制限しますか?
PHP では、置換を制限するパラメーターを受け取る preg_replace を使用してこれを簡単に行うことができますが、Ruby でこれを行う方法がわかりません。
カウンターを作成し、gsub ループ内でデクリメントできます。
str = 'aaaaaaaaaa'
count = 5
p str.gsub(/a/){if count.zero? then $& else count -= 1; 'x' end}
# => "xxxxxaaaaa"
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