In regards to adding an key => value
pair to an existing populated hash in Ruby, I'm in the process of working through Apress' Beginning Ruby and have just finished the hashes chapter.
I am trying to find the simplest way to achieve the same results with hashes as this does with arrays:
x = [1, 2, 3, 4]
x << 5
p x
You might get your key and value from user input, so you can use Ruby .to_sym can convert a string to a symbol, and .to_i will convert a string to an integer.
For example:
If you want to add more than one:
If you have a hash, you can add items to it by referencing them by key:
Here, like
[ ]
creates an empty array,{ }
will create a empty hash.Arrays have zero or more elements in a specific order, where elements may be duplicated. Hashes have zero or more elements organized by key, where keys may not be duplicated but the values stored in those positions can be.
Hashes in Ruby are very flexible and can have keys of nearly any type you can throw at it. This makes it different from the dictionary structures you find in other languages.
It's important to keep in mind that the specific nature of a key of a hash often matters:
Ruby on Rails confuses this somewhat by providing HashWithIndifferentAccess where it will convert freely between Symbol and String methods of addressing.
You can also index on nearly anything, including classes, numbers, or other Hashes.
Hashes can be converted to Arrays and vice-versa:
When it comes to "inserting" things into a Hash you may do it one at a time, or use the
merge
method to combine hashes:Note that this does not alter the original hash, but instead returns a new one. If you want to combine one hash into another, you can use the
merge!
method:Like many methods on String and Array, the
!
indicates that it is an in-place operation.