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

时间:2022-09-08 12:19:39

My case:

我的情况:

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

i want to replace value of text to "[B] and [C]"

我想把文本的值替换为[B]和[C]

How can i do that? Thanks a lot!

我怎么做呢?谢谢!

1 个解决方案

#1


7  

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

#1


7  

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