If you have a hash, you can add elements to it by referencing them with the key:
hash = { } hash[:a] = 'a' hash[:a]
Here, like [ ] , an empty array is created, { } will create an empty hash.
Arrays have zero or more elements in a specific order, where elements can be duplicated. Hashes have zero or more elements organized by the key, where the keys may not be duplicated, but the values โโstored in these positions may be.
Ruby hashes are very flexible and can have keys of almost any type that you can throw at it. This makes it different from dictionary structures that you will find in other languages.
It is important to remember that the specific nature of the hash key often matters:
hash = { :a => 'a' }
Ruby on Rails is a bit confusing by providing a HashWithIndifferentAccess where it will be free to convert between the Symbol and String addressing methods.
You can also index almost everything, including classes, numbers, or other hashes.
hash = { Object => true, Hash => false } hash[Object] # => true hash[Hash] # => false hash[Array] # => nil
Hashes can be converted to arrays and vice versa:
When it comes to โinsertingโ things into a hash, you can do this one at a time or use the merge method to combine hashes:
{ :a => 'a' }.merge(:b => 'b')
Note that this does not change the original hash, but instead returns a new one. If you want to combine one hash into another, you can use the merge! method merge! :
hash = { :a => 'a' }
Like many methods in String and Array,! indicates that this is an on-site operation.