user6327992 user6327992 - 6 months ago 13
Ruby Question

Hash with default value that depends on the key

I have a string and a hash with a default value of

"*"
:

my_string = "a b c d"
my_hash = Hash.new("*")
my_hash["a"] = 1
my_hash["b"] = 2


Then I do

new_string = my_string.gsub(/[abcd]/, my_hash)
# => "1 2 * *"


How can I make
new_string
also include the string that couldn't be found in
my_hash
and have

new_string # => "1 2 *c *d"

Answer
my_hash = Hash.new{|_, k| "*#{k}"}
my_hash["a"] = 1
my_hash["b"] = 2
my_string.gsub(/[abcd]/, my_hash)
# => "1 2 *c *d"