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
  2. Create an Inventory class with:
    • Initialize with empty products array
    • add_product(product) method
    • find_product(name) method - returns product or nil
    • total_inventory_value method - sum of all products' total_value
    • list_products method - returns array of product summaries
  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

Hint 8

File.readlines(file).each reads and iterates over each line

Provided Files (Read-only)

1. Basic inventory operations

Input:
process_inventory('inventory.txt')
Expected Output:
INVENTORY REPORT
==================================================
Laptop: Qty 15 @ $999.99 each (Total: $14999.85)
Mouse: Qty 40 @ $29.99 each (Total: $1199.60)
--------------------------------------------------
Total Inventory Value: $16199.45

2. Multiple products

Input:
process_inventory('inventory.txt')
Expected Output:
INVENTORY REPORT
==================================================
Laptop: Qty 15 @ $999.99 each (Total: $14999.85)
Mouse: Qty 50 @ $29.99 each (Total: $1499.50)
Keyboard: Qty 25 @ $79.99 each (Total: $1999.75)
--------------------------------------------------
Total Inventory Value: $18499.10

3. Sell all stock

Input:
process_inventory('inventory.txt')
Expected Output:
INVENTORY REPORT
==================================================
Widget: Qty 0 @ $5.00 each (Total: $0.00)
--------------------------------------------------
Total Inventory Value: $0.00
+ 2 hidden test cases