Challenge

Problem

Object-oriented programming is fundamental to building maintainable Ruby applications. This drill teaches you to design classes with initialization, instance methods, state management, and data validation. You'll create an inventory system that tracks products with names, quantities, and prices, learning class design, attr_accessor usage, instance variables, and methods that modify object state—essential skills for building real-world Ruby applications.

Difficulty: Intermediate

Instructions

  1. Create a Product class with:
    • Initialize with name, quantity (default 0), price (default 0.0)
    • Attributes: name (read-only), quantity, price
    • add_stock(amount) method - increases quantity
    • remove_stock(amount) method - decreases quantity, returns false if insufficient
    • total_value method - returns quantity * price
    • in_stock? method - returns true if quantity > 0
    • to_s method - returns formatted string
  2. Create an Inventory class with:
    • Initialize with empty products array
    • add_product(product) method
    • find_product(name) method - returns product or nil (case-insensitive)
    • total_inventory_value method - sum of all products' total_value
    • list_products method - returns array of product strings
  3. Read commands from inventory.txt and execute them
  4. Print final inventory report

Files

Editable
Read-only

Hints

Hint 1

attr_reader :name creates a getter method for @name

Hint 2

attr_accessor :quantity creates both getter and setter for @quantity

Hint 3

Use @variable for instance variables inside classes

Hint 4

array.find { |item| condition } returns first matching item

Hint 5

Use .downcase for case-insensitive string comparison

Hint 6

array.sum(&:method_name) sums results of calling method on each item

Hint 7

Format price with '%.2f' % number for 2 decimal places

Ruby 3.4

Provided Files (Read-only)

1. Correct inventory report

Input:
process_inventory('inventory.txt')
Expected Output:
INVENTORY REPORT
==================================================
Laptop: Qty 12 @ $999.99 each (Total: $11999.88)
Mouse: Qty 55 @ $29.99 each (Total: $1649.45)
Keyboard: Qty 30 @ $79.99 each (Total: $2399.70)
--------------------------------------------------
Total Inventory Value: $16049.03

2. Product class works

Input:
p = Product.new('Test', 10, 5.00)
p.add_stock(5)
puts p.to_s
Expected Output:
Test: Qty 15 @ $5.00 each (Total: $75.00)

3. Remove stock returns false if insufficient

Input:
p = Product.new('Test', 5, 10.00)
puts p.remove_stock(10)
puts p.quantity
Expected Output:
false
5
+ 6 hidden test cases