Ruby multiple string replacement

Sayuj picture Sayuj · Nov 15, 2011 · Viewed 64k times · Source
str = "Hello☺ World☹"

Expected output is:

"Hello:) World:("

I can do this: str.gsub("☺", ":)").gsub("☹", ":(")

Is there any other way so that I can do this in a single function call?. Something like:

str.gsub(['s1', 's2'], ['r1', 'r2'])

Answer

Naren Sisodiya picture Naren Sisodiya · Nov 15, 2011

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.

Like this:

'hello'.gsub(/[eo]/, 'e' => 3, 'o' => '*')    #=> "h3ll*"
'(0) 123-123.123'.gsub(/[()-,. ]/, '')    #=> "0123123123"

In Ruby 1.8.7, you would achieve the same with a block:

dict = { 'e' => 3, 'o' => '*' }
'hello'.gsub /[eo]/ do |match|
   dict[match.to_s]
 end #=> "h3ll*"