Challenge

Problem

Command-line tools are the backbone of automation and system administration. This drill teaches you to build a simple CLI calculator that parses command-line arguments, validates input, performs calculations, and provides helpful usage instructions. You'll learn ARGV parsing, input validation, error handling, and user-friendly CLI design—skills essential for building Ruby scripts, automation tools, and system utilities.

Difficulty: Beginner

Instructions

  1. Accept operation and two numbers as arguments
  2. Support basic operations: add, subtract, multiply, divide
  3. Validate:
    • Operation is one of: add, subtract, multiply, divide
    • Both numbers are valid numeric values
  4. Perform calculation and print result formatted to 2 decimal places
  5. Handle division by zero with error message
  6. Print usage instructions if operation is invalid

Files

Editable

Hints

Hint 1

Use Float(string) to convert string to float - raises ArgumentError if invalid

Hint 2

Check array.include?(value) to validate operation

Hint 3

Use case/when for multiple conditions

Hint 4

Check n2 == 0 before dividing

Hint 5

Format with printf style: '%.2f' % number rounds to 2 decimals

Hint 6

rescue ArgumentError catches invalid number conversions

Ruby 3.4

1. Add two numbers

Input:
calculate('add', '10', '5')
Expected Output:
Result: 15.00

2. Subtract two numbers

Input:
calculate('subtract', '10', '5')
Expected Output:
Result: 5.00

3. Multiply two numbers

Input:
calculate('multiply', '10', '5')
Expected Output:
Result: 50.00

4. Divide two numbers

Input:
calculate('divide', '10', '5')
Expected Output:
Result: 2.00

5. Division by zero

Input:
calculate('divide', '10', '0')
Expected Output:
Error: Cannot divide by zero
+ 4 hidden test cases