Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Append a value in a hash object (in Ruby), using an already existing key?

Tags:

ruby

How can I append a value in a Hash object using a key that already has a value. So for example if I have

>> my_hash = Hash.new
>> my_hash[:my_key] = "Value1"
# then append a value, lets say "Value2" to my hash, using that same key "my_key"
# so that it can be
>> my_hash[:my_key]
=> ["Value1", "Value2"]

I know its easy to write my own method, but I just wanted to know if there is a built in method.

like image 422
bernabas Avatar asked Feb 10 '12 19:02

bernabas


2 Answers

I don't know if I'm missing your point but have you considered the following:

1.9.3 (main):0 > h={}
=> {}
1.9.3 (main):0 > h[:key] = []
=> []
1.9.3 (main):0 > h[:key] << "value1"
=> ["value1"]
1.9.3 (main):0 > h[:key] << "value2"
=> ["value1", "value2"]
1.9.3 (main):0 > h[:key]
=> ["value1", "value2"]
like image 103
lucapette Avatar answered Oct 25 '22 09:10

lucapette


The Ruby Way, 2nd Edition has a whole chapter on multi-value hashes if I recall correctly. Regardless, there's no builtin for this behaviour.

However, you can have some fun with passing a block into Hash.new.

$ irb
>> h = Hash.new { |hash, key| hash[key] = [] }
=> {}
>> h[:a] << "Value1"
=> ["Value1"]
>> h[:a] << "Value2"
=> ["Value1", "Value2"]
>> h
=> {:a=>["Value1", "Value2"]}
>> 

If you want []= to always append to the value, then you'll need to monkey patch. Again, nothing built in to work that way.

like image 41
Travis Avatar answered Oct 25 '22 10:10

Travis