Replace words in a string - Ruby

Mithun Sasidharan picture Mithun Sasidharan · Dec 5, 2011 · Viewed 368.4k times · Source

I have a string in Ruby:

sentence = "My name is Robert"

How can I replace any one word in this sentence easily without using complex code or a loop?

Answer

srcspider picture srcspider · Jan 2, 2013
sentence.sub! 'Robert', 'Joe'

Won't cause an exception if the replaced word isn't in the sentence (the []= variant will).

How to replace all instances?

The above replaces only the first instance of "Robert".

To replace all instances use gsub/gsub! (ie. "global substitution"):

sentence.gsub! 'Robert', 'Joe'

The above will replace all instances of Robert with Joe.