0
0
Rubyprogramming~30 mins

Each for iteration in Ruby - Mini Project: Build & Apply

Choose your learning style9 modes available
Using Each For Iteration in Ruby
📖 Scenario: You work in a small bookstore. You have a list of book titles and their prices. You want to print each book's name and price to share with your team.
🎯 Goal: Build a Ruby program that uses each with for iteration to go through a hash of books and prices, then print each book and its price.
📋 What You'll Learn
Create a hash called books with exact keys and values
Create a variable called total_price and set it to 0
Use for title, price in books.each to iterate over the hash
Add each price to total_price
Print each book title and price inside the loop
After the loop, print the total price
💡 Why This Matters
🌍 Real World
Bookstores and shops often need to list items with prices and calculate totals for sales or inventory.
💼 Career
Knowing how to iterate over collections and sum values is a basic skill for many programming jobs, especially in retail or data processing.
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 with keys and values separated by =>.

2
Create a total price variable
Create a variable called total_price and set it to 0
Ruby
Need a hint?

Use = to assign 0 to total_price.

3
Use each for iteration to sum prices and print books
Use for title, price in books.each to iterate over the books hash. Inside the loop, add price to total_price and print the book title and price using puts with the format: "Title: #{title}, Price: $#{price}"
Ruby
Need a hint?

Use for title, price in books.each to loop. Use total_price += price to add prices. Use puts with string interpolation to print.

4
Print the total price
After the loop, print the total price using puts with the format: "Total price: $#{total_price}"
Ruby
Need a hint?

Use puts after the loop to print the total price with string interpolation.