jcarpio jcarpio - 7 months ago 4
Ruby Question

Append key/value pair to hash with << in Ruby

In Ruby, one can append values to existing arrays using <<:

a = []
a << "foo"


but, can you also append key/value pairs to an existing hash?

h = {}
h << :key "bar"


I know you can do:

h[:key] = ""
h[:key] << "bar"


but that's not I want.

Thanks.

Answer

There is merge!.

h = {}
h.merge!(key: "bar")
# => {:key=>"bar"}
Comments