Add value to a hash object (in Ruby) using an existing key?

How to add a value to 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 your own method, but I just wanted to know if there is a built-in method.

+7
source share
2 answers

I do not know if I am missing your point, but 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"] 
+9
source

Ruby Way, 2nd Edition has a whole chapter on multi-valued hashes, if I remember correctly. Despite this, there are no built-in functions for this behavior.

However, you can have some fun with passing the block to 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 []= always add a value, you need to install the monkey patch. Again, nothing is created to work this way.

+9
source

All Articles