Goalie Goalie - 3 months ago 16
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


My one liner:

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

or using String#sub! method:

hash.each { |k, v| str.sub!(k, v) }