I'm new to Ruby and don't know how to add new item to already existing hash. For example, first I construct hash:
hash = {item1: 1}
after that a want to add item2 so after this I have hash like this:
{item1: 1, item2: 2}
I don't know what method to do on hash, could someone help me?
hash[key]=value Associates the value given by value with the key given by key.
From Ruby documentation: http://www.tutorialspoint.com/ruby/ruby_hashes.htm
Create hash as:
Now insert into hash as:
If you want to add new items from another hash - use
merge
method:In your specific case it could be:
but it's not wise to use it when you should to add just one element more.
Pay attention that
merge
will replace the values with the existing keys:exactly like
hash[:item1] = 2
Also you should pay attention that
merge
method (of course) doesn't effect the original value of hash variable - it returns a new merged hash. If you want to replace the value of the hash variable then usemerge!
instead:Create the hash:
Add a new item to it:
hash.store(key, value) - Stores a key-value pair in hash.
Example:
Documentation