我试图在Ruby中进行多次替换。我会用PHP做的:
$text = "bar foo baz doom?";
$before = ["bar", "foo", "baz"];
$after = ["goto", "if", "else"];
$result = preg_replace($before, $after, $text);
// output: goto if else doom?
在Ruby中,类似下面的内容给我一个错误:
text = "bar foo baz doom?"
before = [/bar/, /foo/, /baz/]
after = ['goto', 'if', 'else']
result = text.gsub(before, after)
# => Can't convert Array into Regexp
你能帮助我吗?
答案 0 :(得分:3)
将Hash
与#gsub
一起使用: -
text = "bar foo baz doom?"
before = ["bar", "foo", "baz"]
after = ["goto", "if", "else"]
hash = Hash[before.zip(after)]
#=> {"bar"=>"goto", "foo"=>"if", "baz"=>"else"}
text.gsub(/\w+/) { |m| hash[m] || m }
#=> "goto if else doom?"
答案 1 :(得分:1)
我认为红宝石中没有相应的方法。您可以zip
before
和after
并逐步应用每个替换。这是一个示例,我使用dup
来防止改变原始内容。
text = "bar foo baz doom?"
before = [/bar/, /foo/, /baz/]
after = ['goto', 'if', 'else']
result = text.dup
before.zip(after).each { |pattern, replace| result.gsub!(pattern, replace) }
result
答案 2 :(得分:1)
text = "bar foo baz doom?"
before = [/bar/, /foo/, /baz/]
after = ['goto', 'if', 'else']
before.each_with_index do |reg, i|
text.gsub!(reg, after[i])
end
答案 3 :(得分:0)
text = "bar foo baz doom?"
before = [/bar/, /foo/, /baz/]
after = ['goto', 'if', 'else']
result = text.dup
before.each_index { |i| result.gsub!(before[i] ,after[i]) }
result
答案 4 :(得分:0)
归档此
的另一种方式output = text.split.map { |x| before.index(x) ? after[before.index(x)] : x }.join(' ')
output
根据要求包含"goto if else doom?"
。
答案 5 :(得分:0)
您可以在ruby 1.9.2及更高版本中使用正则表达式来实现此目的。
class String
def preg_replace(before, after)
gsub Regexp.union(before), Hash[before.zip(after)]
end
end
text = "bar foo baz doom?"
before = ["bar", "foo", "baz"]
after = ["goto", "if", "else"]
text.preg_replace before, after
#=> "goto if else doom?"