0
0
Rubyprogramming~15 mins

Merge and update methods in Ruby - Mini Project: Build & Apply

Choose your learning style9 modes available
Merge and Update Methods
📖 Scenario: You are managing a small online store's inventory. You have a list of products with their current stock counts. Occasionally, you receive new shipments that update the stock counts or add new products.
🎯 Goal: Build a Ruby program that merges two hashes representing product stocks. The program will update existing products' stock counts and add new products from the shipment.
📋 What You'll Learn
Create a hash called current_stock with exact product names and stock counts
Create a hash called new_shipment with exact product names and stock counts
Use the merge! method with a block to update current_stock by adding stock counts from new_shipment
Print the updated current_stock hash
💡 Why This Matters
🌍 Real World
Managing inventory updates in small business software or online stores often requires merging stock data from different sources.
💼 Career
Understanding how to merge and update hashes is useful for backend developers working with data aggregation, inventory systems, or configuration management.
Progress0 / 4 steps
1
Create the current stock hash
Create a hash called current_stock with these exact entries: 'apple' => 30, 'banana' => 15, 'orange' => 20
Ruby
Need a hint?

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

2
Create the new shipment hash
Create a hash called new_shipment with these exact entries: 'banana' => 10, 'orange' => 5, 'grape' => 12
Ruby
Need a hint?

Use the same syntax as the first hash to create new_shipment.

3
Merge and update the stock counts
Use the merge! method on current_stock with new_shipment and a block that adds the old and new stock counts for matching products
Ruby
Need a hint?

The block receives the key, old value, and new value. Return the sum to update the stock count.

4
Print the updated stock
Print the current_stock hash to display the updated stock counts
Ruby
Need a hint?

Use puts to print the hash. The output shows the updated stock counts.