- How do I limit the number of replacements when using 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