Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace words in a string - Ruby

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?

like image 883
Mithun Sasidharan Avatar asked Dec 05 '11 05:12

Mithun Sasidharan


People also ask

How do you replace letters in a string in Ruby?

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!"

How do you replace multiple characters in a string in Ruby?

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 '-'.

How do I use GSUB in Ruby?

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.

What is .TR in Ruby?

The tr() is an inbuilt method in Ruby returns the trace i.e., sum of diagonal elements of the matrix.


1 Answers

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.

like image 102
srcspider Avatar answered Sep 26 '22 03:09

srcspider