我可以想到gsub像这样使用块:
count = 0
str.gsub(/pat/) { |a| count+=1; "replacement" }
Run Code Online (Sandbox Code Playgroud)
例:
str = "lets replace all s with S"
count = 0
str.gsub("s") { |a| count+=1; "S" }
count
#=> 2
Run Code Online (Sandbox Code Playgroud)