3

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]"

How can i do that? Thanks a lot!

1 Answer 1

8
text.gsub(/\[\w+\]/, Hash[search.zip replace])
# => "[B] and [C]"
Sign up to request clarification or add additional context in comments.

5 Comments

Thank you! it seem good. can i ask more? i have this case: text = "[A#] and [B]", search = ["[A#]", "[B]", "[C]", "[D]", "[Aa]"], replace = ["[B]", "[C]", "[D]", "[E]", "[Bb]"], and i still want to replace value of text to "[B] and [C]". How can i modify your method to use it?
Just add # to gsub part, like this: .gsub(/\[\w+\#*\]/,
Thank you @YevgeniyAnfilofyev, i tried to use .gsub(/\[\w+#\]/, and i forgot * after #
Another option is to build the regular expression from the input array: text.gsub(Regexp.union(search), search.zip(replace).to_h)
This is a great answer, as is @Stefan's comment which makes it work for arbitrary search strings.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.