0

我想在给定字符串的一部分中替换所有对.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'}上不起作用。

4

2 回答 2

3

正如@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}."
于 2013-10-18T14:02:15.797 回答
2

将 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}."
于 2013-10-18T13:30:23.500 回答