jcarpio jcarpio - 2 years ago 57
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