Goalie Goalie - 1 month ago 6
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
key
with hash collection
value
in a string?

eg my input string:
str = I want a 3


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

Answer

My one liner:

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

or using String#sub! method:

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