Menu
Coddy logo textTech

Creating Hashes

Part of the Fundamentals section of Coddy's Ruby journey — lesson 73 of 88.

Arrays are great for storing ordered lists, but sometimes you need to associate values with specific labels rather than numeric indexes. A hash stores data as key-value pairs, where each key points to a corresponding value.

To create a hash, use curly braces with keys and values separated by => (called a hash rocket):

person = {"name" => "Alice", "age" => 25, "city" => "Paris"}

puts person  # Outputs: {"name"=>"Alice", "age"=>25, "city"=>"Paris"}

Each key must be unique within the hash, but values can repeat. Keys and values can be any data type, including strings, numbers, or even arrays.

You can also create an empty hash and add pairs later:

scores = {}

puts scores  # Outputs: {}

Hashes are perfect for representing real-world objects with named attributes, like a product with a name and price, or a user with an email and password. Unlike arrays where you remember positions, hashes let you use meaningful names to organize your data.

challenge icon

Challenge

Easy

Read three lines of input:

  1. A book title (string)
  2. An author name (string)
  3. A publication year (integer)

Create a hash called book with three key-value pairs using the hash rocket syntax (=>):

  • "title" mapped to the book title
  • "author" mapped to the author name
  • "year" mapped to the publication year (as an integer)

Print the hash using puts.

For example, if the inputs are Ruby Basics, Jane Smith, and 2023, the output should be:

{"title"=>"Ruby Basics", "author"=>"Jane Smith", "year"=>2023}

If the inputs are The Great Gatsby, F. Scott Fitzgerald, and 1925, the output should be:

{"title"=>"The Great Gatsby", "author"=>"F. Scott Fitzgerald", "year"=>1925}

If the inputs are 1984, George Orwell, and 1949, the output should be:

{"title"=>"1984", "author"=>"George Orwell", "year"=>1949}

Cheat sheet

A hash stores data as key-value pairs, where each key points to a corresponding value.

To create a hash, use curly braces with keys and values separated by => (hash rocket):

person = {"name" => "Alice", "age" => 25, "city" => "Paris"}

puts person  # Outputs: {"name"=>"Alice", "age"=>25, "city"=>"Paris"}

Each key must be unique within the hash, but values can repeat. Keys and values can be any data type, including strings, numbers, or arrays.

You can create an empty hash:

scores = {}

puts scores  # Outputs: {}

Try it yourself

# Read input
title = gets.chomp
author = gets.chomp
year = gets.to_i

# TODO: Create a hash called 'book' with three key-value pairs using hash rocket syntax (=>)
# Keys should be: "title", "author", "year"


# Output the hash
puts book
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Fundamentals