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. Parse command-line arguments from ARGV
  2. Support basic operations: add, subtract, multiply, divide
  3. Accept format: ruby calc.rb <operation> <num1> <num2>
  4. Validate:
    • Exactly 3 arguments provided
    • Operation is one of: add, subtract, multiply, divide
    • Both numbers are valid numeric values
  5. Perform calculation and print result
  6. Handle division by zero with error message
  7. Print usage instructions if arguments invalid
  8. Usage format:
    'Usage: ruby calc.rb '
    'Operations: add, subtract, multiply, divide'

Files

Editable

Hints

Hint 1

ARGV is an array containing command-line arguments

Hint 2

ARGV[0] is the first argument, ARGV[1] is second, etc.

Hint 3

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

Hint 4

Check array.include?(value) to validate operation

Hint 5

Use case/when for multiple conditions

Hint 6

Check n2 == 0 before dividing

Hint 7

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

Hint 8

rescue ArgumentError catches invalid number conversions

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