Explanation of Hashes


I just need someone that can help explain how exactly hashes work. I understand that hashes are more or less arrays that use strings instead of numbers, but I dont understand Hash.new. How do you add new things to it, change things already in it, and remove things from it. Thanks in advance!


A hash is akin to an associative array, which consists of key->value pairs. The equivalent in Python is a dictionary, and in JavaScript, an ‘object’.

Hashes are unordered which means the order of insertion is not remembered. When printing a hash we cannot predict the order it will display.

You have observed that keys are always string type, even when the are written as numbers.

Adding to a hash is a simple matter of subscripting the value to a key:

my_hash['colors'] = ['red', 'orange', 'yellow', 'green', 'blue', 'violet']

Changing the value associated with a key is done in the exact same manner.

Removing an item from the hash is done with the delete function.

delete(my_hash, 'colors')

This could be wrong, or rather the internal approach. In method form,



Okay so is

my_hash[‘colors’] = [‘red’, ‘orange’, ‘yellow’, ‘green’, ‘blue’, ‘violet’]

the same thing as this?

my_hash = { “colors” => “red”,
“colors” => “orange”,
“colors” => “yellow”,
“colors” => “green”,
“colors” => “blue”,
“colors” => “violet”}


No, keys cannot be duplicated. The example gives one key, with an array as the associated value/object.

In a literal,

my_hash = { colors => [ ... ] }

We could add to the array in the hash with Array.push():



This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.