jcarpio jcarpio - 1 year ago 54
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.


Answer Source

There is merge!.

h = {}
h.merge!(key: "bar")
# => {:key=>"bar"}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download