Answer the question
In order to leave comments, you need to log in
How to replace multiple words in a string with ruby?
There is a certain line: sentence = "My name is Robert"
I need to replace words My
with Your
and Robert
with Joe
I did this:
In this case, the necessary replacement of the word occurs, but how can I replace 2 words at the same time?
I tried something like this, but it didn't worksentence.gsub! 'Robert', 'Joe'
sentence.gsub! 'Robert', 'Joe'.gsub "My", "Your"
Answer the question
In order to leave comments, you need to log in
Just space the brackets so that there is no confusion.
sentence.gsub('Robert', 'Joe').gsub('My', 'Your')
=> "Your name is Joe"
sub
. sentence.gsub(/Robert|My/, 'Robert' => 'Joe', 'My' => 'Your')
=> "Your name is Joe"
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question