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 valuesCreate a variable called
total_price and set it to 0Use
for title, price in books.each to iterate over the hashAdd each
price to total_pricePrint 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