S
S
Stergy2019-06-09 19:32:53
ruby
Stergy, 2019-06-09 19:32:53

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 Yourand Robertwith 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 work
sentence.gsub! 'Robert', 'Joe'
sentence.gsub! 'Robert', 'Joe'.gsub "My", "Your"

Answer the question

In order to leave comments, you need to log in

1 answer(s)
O
oh_shi, 2019-06-09
@Stergy

Just space the brackets so that there is no confusion.

sentence.gsub('Robert', 'Joe').gsub('My', 'Your')
=> "Your name is Joe"

But if the word to be replaced in the string occurs only 1 time, then it is better to use sub.
And if you really want for 1 pass along the line
sentence.gsub(/Robert|My/, 'Robert' => 'Joe', 'My' => 'Your')
=> "Your name is Joe"

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question