将表达式应用于ruby搜索并替换为regexp



我知道在ruby中,可以使用gsub和正则表达式搜索和替换字符串。

然而,可以将表达式应用于搜索结果,并在替换之前进行替换。

例如,在下面的代码中,虽然可以将匹配的字符串与一起使用,但不能对其应用表达式(例如.to_i * 10),这样做会导致错误:

shopping_list = <<LIST
3 apples
500g flour
1 ham
LIST
new_list = shopping_list.gsub(/d+/m, .to_i * 10)
puts new_list #syntax error, unexpected $undefined

它似乎只适用于字符串文字:

shopping_list = <<LIST
3 apples
500g flour
1 ham
LIST
new_list = shopping_list.gsub(/d+/m, ' string and replace')
puts new_list

这就是您想要的吗?

shopping_list = <<LIST
3 apples
500g flour
1 ham
LIST
new_list = shopping_list.gsub(/d+/m) do |m|
  m.to_i * 10
end
puts new_list 
# >> 30 apples
# >> 5000g flour
# >> 10 ham

文档:String#gsub。

最新更新