Goalie Goalie - 1 year ago 63
Ruby Question

How do you replace a string with a hash collection value in Ruby?

I have a hash collection:

my_hash = {"1" => "apple", "2" => "bee", "3" => "cat"}

What syntax would I use to replace the first occurrence of the
with hash collection
in a string?

eg my input string:
str = I want a 3

The resulting string would be:
str = I want a cat

Answer Source

My one liner:

hash.each { |k, v| str[k] &&= v }

or using String#sub! method:

hash.each { |k, v| str.sub!(k, v) }
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download