8

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.

2 Answers 2

10

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"]
Sign up to request clarification or add additional context in comments.

1 Comment

oh ok...so basically i'm just using an array inside a hash... what happened was that when I tried to do h[:key] << "value2" with out doing h[:key]=[], and it kept concatenating the strings and returning "value1value2", so i guess i have to explicitly make an array..thanks
9

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.

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.