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

jcarpio picture jcarpio · Nov 3, 2013 · Viewed 169.4k times · Source

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

sawa picture sawa · Nov 3, 2013

There is merge!.

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