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

ruby

Solution

My one liner:

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

or using `String#sub!` method:

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

Problem

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`

Original source