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?
sentence.sub! 'Robert', 'Joe'
Won't cause an exception if the replaced word isn't in the sentence (the []=
variant will).
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.