Victor Victor - 2 years ago 235
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 Source

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"


a = "every good boy does fine"
h = {"every" => "all","boy" => "girl", "fine" =>"well" }"^#{h.keys.join('|')}$") # => /^every|boy|fine$/
# => "all good girl does well"
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download