获取Ruby中gsub替换的数量

时间:2015-09-22 11:53:20

标签: ruby

gsub returns字符串,或nil。有没有办法让它返回它所取代的替换数量?

2 个答案:

答案 0 :(得分:5)

我可以考虑像这样使用gsub块:

count = 0
str.gsub(/pat/) { |a| count+=1; "replacement" }

示例:

str = "lets replace all s with S"
count = 0
str.gsub("s") { |a| count+=1; "S" }
count
#=> 2

答案 1 :(得分:3)

在没有第二个参数的Ruby gsub中返回Enumerator,您可以使用它:

str = 'your string'
new_str = str.gsub(/your/, 'my')
count = str.gsub(/your/).count
相关问题