What are hashes in Ruby?

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.

Create a hash in Ruby

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 hash
myhash = { "foo"=> 5, "bar"=>"my value", "k"=> 73 }
# Output a value against a key
puts myhash["k"]

Renaming a key-value pair

A value can also be reassigned against a key. The syntax to do this is shown below.

# Create hash
myhash = { "foo"=> 5, "bar"=>"my value", "k"=> 73 }
# Output a value against a key
puts myhash["k"]
# Reassign a value to a key
myhash["k"] = 20
# Output the new value against a key
puts myhash["k"]

Adding a new key-value pair to the hash

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 hash
myhash = { "foo"=> 5, "bar"=>"my value", "k"=> 73 }
# Add a new key value pair
myhash["new value"] = 30
puts myhash
# Referencing a non existent key. Nothing is outputted
puts myhash["Non-existent key"]
New on Educative
Learn to Code
Learn any Language as a beginner
Develop a human edge in an AI powered world and learn to code with AI from our beginner friendly catalog
🏆 Leaderboard
Daily Coding Challenge
Solve a new coding challenge every day and climb the leaderboard

Free Resources