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?
The simplest way to replace a string in Ruby is to use the substring replacement. We can specify the string to replace inside a pair of square brackets and set the replace value: For example: msg = "Programming in Ruby is fun!"
You can use a regular expression to match the substring that needs to be replaced and pass hash for values to be replaced. @NarenSisodiya, actually it should be: '(0) 123-123.123'. gsub(/[()\-,. ]/, '') You need to add the escape character to '-'.
gsub! is a String class method in Ruby which is used to return a copy of the given string with all occurrences of pattern substituted for the second argument. If no substitutions were performed, then it will return nil. If no block and no replacement is given, an enumerator is returned instead.
The tr() is an inbuilt method in Ruby returns the trace i.e., sum of diagonal elements of the matrix.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With