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.
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"]
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With