Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby gsub multiple characters in string

Using Ruby 1.9.3, Rails 3.2, I have the following:

"every good boy does fine".gsub("every", "all").gsub("boy", "girl").gsub("fine", "well")
# => "all good girl does well"

Is there a better way to write this? Thanks.

like image 515
Victor Avatar asked Dec 18 '13 05:12

Victor


People also ask

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

Since Ruby 1.9. 2, String#gsub accepts hash as a second parameter for replacement with matched keys. You can use a regular expression to match the substring that needs to be replaced and pass hash for values to be replaced.

What is the difference between gsub () and sub ()?

The sub() and gsub() function in R is used for substitution as well as replacement operations. The sub() function will replace the first occurrence leaving the other as it is. On the other hand, the gsub() function will replace all the strings or values with the input strings.

What does .gsub mean 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.

Does GSUB use regex?

Regular expressions (shortened to regex) are used to operate on patterns found in strings. They can find, replace, or remove certain parts of strings depending on what you tell them to do.


1 Answers

String#gsub and Hash#fetch will be the good choice for this.

a = "every good boy does fine"
h = {"every" => "all","boy" => "girl", "fine" =>"well" }
a.gsub(/\w+/) { |m| h.fetch(m,m)}
# => "all good girl does well"

or,

a = "every good boy does fine"
h = {"every" => "all","boy" => "girl", "fine" =>"well" }
Regexp.new("^#{h.keys.join('|')}$") # => /^every|boy|fine$/
a.gsub(Regexp.new("^#{h.keys.join('|')}$"),h)
# => "all good girl does well"
like image 56
Arup Rakshit Avatar answered Sep 25 '22 11:09

Arup Rakshit