Victor Victor - 7 months ago 32
Ruby Question

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.

Answer

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"