How to simply extract the replacement as an argument and encapsulate the counter by blocking the block above it inside the method?
str = "aaaaaaaaaaaaaaa" def replacements(replacement, limit) count = limit lambda { |original| if count.zero? then original else count -= 1; replacement end } end p str.gsub(/a/, &replacements("x", 5))
You can make this even more general by using a replacement block:
def limit(n, &block) count = n lambda do |original| if count.zero? then original else count -= 1; block.call(original) end end end
Now you can do things like
p str.gsub(/a/, &limit(5) { "x" }) p str.gsub(/a/, &limit(5, &:upcase))
hammar
source share