A hash is a collection of unique key-value pairs. Hashes are similar to arrays in the way that they store the values against an index. However, arrays use an integer as an index, whereas hashes use object types as an index. A hash assigns values to keys, thus, enabling values to be looked up by their keys.
A hash is created by writing the key-value pairs inside curly braces ({}
). Values can be accessed by writing the keys in square brackets.
# Create hashmyhash = { "foo"=> 5, "bar"=>"my value", "k"=> 73 }# Output a value against a keyputs myhash["k"]
A value can also be reassigned against a key. The syntax to do this is shown below.
# Create hashmyhash = { "foo"=> 5, "bar"=>"my value", "k"=> 73 }# Output a value against a keyputs myhash["k"]# Reassign a value to a keymyhash["k"] = 20# Output the new value against a keyputs myhash["k"]
We can also add new key value pairs to hashes after the initialization. The code below shows that when we reference a non-existent key the output is nothing.
# Create hashmyhash = { "foo"=> 5, "bar"=>"my value", "k"=> 73 }# Add a new key value pairmyhash["new value"] = 30puts myhash# Referencing a non existent key. Nothing is outputtedputs myhash["Non-existent key"]