0
0
Rubyprogramming~30 mins

Block syntax (do..end and curly braces) in Ruby - Mini Project: Build & Apply

Choose your learning style9 modes available
Block syntax (do..end and curly braces)
📖 Scenario: You are helping a small bakery keep track of daily sales. Each sale has a product name and the quantity sold. You want to use Ruby blocks to process this sales data.
🎯 Goal: Learn how to use Ruby blocks with both do..end and curly braces {} syntax to iterate over sales data and calculate total items sold.
📋 What You'll Learn
Create a hash called sales with exact product names and quantities
Create a variable total_items to hold the sum of all quantities
Use a do..end block with each to add quantities to total_items
Use a curly braces {} block with each to print each product and quantity
Print the total number of items sold
💡 Why This Matters
🌍 Real World
Blocks let you process collections like sales data easily, which is common in business apps.
💼 Career
Understanding block syntax is essential for Ruby developers working on data processing, web apps, and automation.
Progress0 / 4 steps
1
Create the sales data hash
Create a hash called sales with these exact entries: 'Bread' => 10, 'Cake' => 5, 'Pie' => 7
Ruby
Need a hint?

Use curly braces {} to create the hash with keys and values separated by =>.

2
Create a total_items variable
Create a variable called total_items and set it to 0
Ruby
Need a hint?

Just write total_items = 0 to start counting from zero.

3
Use a do..end block to sum quantities
Use sales.each do |product, quantity| ... end to add each quantity to total_items
Ruby
Need a hint?

Use each do |product, quantity| ... end to loop through the hash and add quantities.

4
Use curly braces block to print sales and print total
Use sales.each { |product, quantity| puts "#{product}: #{quantity}" } to print each product and quantity. Then print total_items with puts total_items
Ruby
Need a hint?

Use curly braces {} with each to print each item. Use puts total_items to show the total.