Ruby:如何用两个数组替换字符串中的单词?

时间:2015-03-25 07:35:51

标签: ruby

我的情况:

text = "[A] and [B]"
search = ["[A]", "[B]", "[C]", "[D]", "[Aa]"]
replace = ["[B]", "[C]", "[D]", "[E]", "[Bb]"]

我想将text的值替换为"[B] and [C]"

我该怎么做?非常感谢!

1 个答案:

答案 0 :(得分:8)

text.gsub(/\[\w+\]/, Hash[search.zip replace])
# => "[B] and [C]"