96

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.

2
  • 26
    Why not h[:key] = "bar"?
    – Hauleth
    Nov 3, 2013 at 18:21
  • 7
    This doesn't work: h[:key] << "bar" Dec 11, 2017 at 14:30

6 Answers 6

161

There is merge!.

h = {}
h.merge!(key: "bar")
# => {:key=>"bar"}
6
  • 4
    I don't think merge! qualifies as simply creating a new key/value pair as it's actually used for another purpose. Nov 3, 2013 at 18:24
  • Good point. I think it may also end up depending on other factors that the OP didn't post. Nov 3, 2013 at 18:25
  • 1
    Ah, thanks. Looks like the store method does something similar. This was mostly an academic question as I've seen << referred as a way to append to arrays but wanted to see if it worked for hashes. Thanks again.
    – jcarpio
    Nov 3, 2013 at 18:41
  • 5
    The difference is this: store simply adds a new pair, it doesn't care if the key already exists. with merge! however, entries with duplicate keys are overridden so the method does a bit more than just adding pairs. If you benchmark the two, you will find store to be faster(trivial however especially on small hashes) Nov 3, 2013 at 18:51
  • 2
    @jcarpio Thanks. Hash#merge! returns the receiver hash just like Array#<< returns the receiver array. Hash#store is a completely different thing. Also, with the hash syntax sugar key: "bar" in the argument position, I thought this was the closest you can get to your notation. I knew this one is closer to what you wanted.
    – sawa
    Nov 4, 2013 at 1:54
106

Since hashes aren't inherently ordered, there isn't a notion of appending. Ruby hashes since 1.9 maintain insertion order, however. Here are the ways to add new key/value pairs.

The simplest solution is

h[:key] = "bar"

If you want a method, use store:

h.store(:key, "bar")

If you really, really want to use a "shovel" operator (<<), it is actually appending to the value of the hash as an array, and you must specify the key:

h[:key] << "bar"

The above only works when the key exists. To append a new key, you have to initialize the hash with a default value, which you can do like this:

h = Hash.new {|h, k| h[k] = ''}
h[:key] << "bar"

You may be tempted to monkey patch Hash to include a shovel operator that works in the way you've written:

class Hash
  def <<(k,v)
    self.store(k,v)
  end
end

However, this doesn't inherit the "syntactic sugar" applied to the shovel operator in other contexts:

h << :key, "bar" #doesn't work
h.<< :key, "bar" #works
3
  • Thorough! Thanks for the contribution and insight.
    – jcarpio
    Nov 4, 2013 at 23:09
  • To note, as of Ruby 1.9, Hashes are ordered.
    – steel
    Jun 26, 2015 at 14:39
  • 1
    Ruby 1.9+ maintains insertion order, but a Hash as a data structure doesn't have the concept of any kind of inherent order. Jun 26, 2015 at 18:01
30

No, I don't think you can append key/value pairs. The only thing closest that I am aware of is using the store method:

h = {}
h.store("key", "value")
0
4

Perhaps you want Hash#merge ?

1.9.3p194 :015 > h={}
 => {} 
1.9.3p194 :016 > h.merge(:key => 'bar')
 => {:key=>"bar"} 
1.9.3p194 :017 > 

If you want to change the array in place use merge!

1.9.3p194 :016 > h.merge!(:key => 'bar')
 => {:key=>"bar"} 
3
  • I don't think merge it's a good idea because it returns a new array; not adding the new pair to the existing hash. Nov 3, 2013 at 18:27
  • How about the merge! (i.e. to existing array) instead of merge ? Nov 3, 2013 at 18:31
  • 1
    merge! technically works in this context but I think it should be used for merging two hashes rather than simply adding a new pair. Also, if you benchmark merge!, it's slower than store ;) Nov 3, 2013 at 18:38
4

Similar as they are, merge! and store treat existing hashes differently depending on keynames, and will therefore affect your preference. Other than that from a syntax standpoint, merge!'s key: "value" syntax closely matches up against JavaScript and Python. I've always hated comma-separating key-value pairs, personally.

hash = {}
hash.merge!(key: "value")
hash.merge!(:key => "value")
puts hash

{:key=>"value"}

hash = {}
hash.store(:key, "value")
hash.store("key", "value")
puts hash

{:key=>"value", "key"=>"value"}

To get the shovel operator << working, I would advise using Mark Thomas's answer.

2

I had to do a similar thing but I needed to add values with same keys. When I use merge or update I can't push values with same keys. So I had to use array of hashes.

    my_hash_static = {:header =>{:company => 'xx', :usercode => 'xx', :password => 'xx',
                      :type=> 'n:n', :msgheader => from}, :body=>[]}
    my_hash_dynamic = {:mp=>{:msg=>message, :no=>phones} }        
    my_hash_full = my_hash_static[:body].push my_hash_dynamic

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.