我想在给定字符串的一部分中替换所有对.
to的引用。看这个例子:_
%{}
'example 1.1 %{a.b.c} of {d.e.f}.'
应更换为
'example 1.1 %{a_b_c} of {d_e_f}.'
我必须这样做,因为在旧的红宝石example %{a.b.c}' % {:'a.b.c' => 'result'}
上不起作用。
正如@sawa 所建议的,稍作调整:
'example 1.1 %{a.b.c} of {d.e.f}.'.gsub(/{.+?}/) { |s| s.tr '.', '_' }
=> "example 1.1 %{a_b_c} of {d_e_f}."
将 gsub 与块一起使用:
data = 'example 1.1 %{a.b.c} of {d.e.f}.'
p data.gsub(/{.+?}/){|x| x.gsub('.','_')} #=> "example 1.1 %{a_b_c} of {d_e_f}."