How to replace multiple words in a string in ruby?

There is a certain line:
sentence = "My name is Robert"
I need to do the replacement of My on Yourand Robert on Joe
Did
sentence.gsub! 'Robert', 'Joe'
In this case, it is necessary to replace the words, but how to make the simultaneous replacement of the 2 words?
I tried something like that, but didn't work
sentence.gsub! 'Robert', 'Joe'.gsub "My", "Your"
March 23rd 20 at 19:47
1 answer
March 23rd 20 at 19:49
Solution
Just place the brackets to avoid confusion.
sentence.gsub('Robert', 'Joe').gsub('My', 'Your')
=> "Your name is Joe"

But if the word you want to replace in the string occurs only 1 time, it is better to use a sub.
And if you really want 1-pass the line
sentence.gsub(/Robert|My/, 'Robert' => 'Joe', 'My' => 'Your')
=> "Your name is Joe"
Thank you so much, you have no idea how I was helped - Devan_Durgan commented on March 23rd 20 at 19:52

Find more questions by tags Ruby