0
0
Rubyprogramming~30 mins

Hash methods (keys, values, each) in Ruby - Mini Project: Build & Apply

Choose your learning style9 modes available
Explore Ruby Hash Methods: keys, values, each
📖 Scenario: You work at a small bookstore. You have a list of books with their prices stored in a Ruby hash. You want to learn how to get all the book titles, all the prices, and how to look at each book and its price one by one.
🎯 Goal: Build a Ruby program that creates a hash of books and prices, stores the list of book titles and prices separately, and then prints each book with its price using a loop.
📋 What You'll Learn
Create a hash called books with these exact entries: 'Ruby Basics' => 25, 'JavaScript Guide' => 30, 'Python 101' => 20
Create a variable called titles that stores all the keys from the books hash
Create a variable called prices that stores all the values from the books hash
Use books.each with block variables title and price to print each book title and its price
💡 Why This Matters
🌍 Real World
Managing collections of items with prices is common in stores, inventories, and online shops. Hashes help store and access this data easily.
💼 Career
Understanding how to work with hashes and their methods is essential for Ruby developers working on backend systems, data processing, and web applications.
Progress0 / 4 steps
1
Create the books hash
Create a hash called books with these exact entries: 'Ruby Basics' => 25, 'JavaScript Guide' => 30, 'Python 101' => 20
Ruby
Need a hint?

Use curly braces {} to create a hash. Separate keys and values with =>.

2
Get all book titles and prices
Create a variable called titles that stores all the keys from the books hash using books.keys. Also create a variable called prices that stores all the values from the books hash using books.values.
Ruby
Need a hint?

Use hash.keys to get all keys and hash.values to get all values.

3
Use each to loop over books
Use books.each with block variables title and price to loop over the hash and print each book title and its price in the format: "Ruby Basics costs $25".
Ruby
Need a hint?

Use each do |key, value| ... end to loop over a hash. Use puts to print.

4
Print titles and prices lists
Print the titles variable and then print the prices variable, each on its own line.
Ruby
Need a hint?

Use puts titles and puts prices to print the arrays.