0
0
Rubyprogramming~15 mins

Each as the primary iterator in Ruby - Mini Project: Build & Apply

Choose your learning style9 modes available
Using Each as the Primary Iterator in Ruby
📖 Scenario: You work at a small bookstore. You have a list of book titles and their prices. You want to print each book's name with its price to show customers.
🎯 Goal: Build a Ruby program that uses each as the primary iterator to go through a hash of books and prices, then print each book with its price.
📋 What You'll Learn
Create a hash called books with these exact entries: 'Ruby Basics' => 25, 'Rails Guide' => 30, 'JavaScript Essentials' => 20
Create a variable called discount and set it to 5
Use each as the primary iterator with variables title and price to go through books
Inside the loop, subtract discount from price and store it in final_price
Print each book's title and its final_price in the format: "Ruby Basics costs $20"
💡 Why This Matters
🌍 Real World
This project shows how to loop through collections of data, like products and prices, which is common in many business applications.
💼 Career
Knowing how to use <code>each</code> to iterate over hashes is a fundamental skill for Ruby developers working with data collections.
Progress0 / 4 steps
1
Create the books hash
Create a hash called books with these exact entries: 'Ruby Basics' => 25, 'Rails Guide' => 30, 'JavaScript Essentials' => 20
Ruby
Need a hint?

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

2
Add a discount variable
Create a variable called discount and set it to 5
Ruby
Need a hint?

Use a simple assignment to create the variable discount.

3
Use each to iterate over books
Use each as the primary iterator with variables title and price to go through books. Inside the loop, subtract discount from price and store it in final_price
Ruby
Need a hint?

Use books.each do |title, price| ... end to loop. Calculate final_price inside the loop.

4
Print each book's title and final price
Inside the each loop, print each book's title and its final_price in the format: "Ruby Basics costs $20"
Ruby
Need a hint?

Use puts with string interpolation: "#{title} costs $#{final_price}".