Menu
Coddy logo textTech

Recap - Safe Calculator

Part of the Logic & Flow section of Coddy's Ruby journey — lesson 47 of 56.

Build a small calculator that survives bad input, combining raise, multiple rescue clauses, and ensure.

challenge icon

Challenge

Medium

Define a method calc(a, op, b) that:

  • Raises ArgumentError with message "unknown operator" if op is not one of +, -, *, /
  • Performs the operation otherwise (use integer arithmetic for /)

Then read three lines from input, a, op, b: and call calc inside begin / rescue / ensure:

  • On success, print <a> <op> <b> = <result>
  • On ArgumentError, print Bad operator
  • On ZeroDivisionError, print Cannot divide by zero
  • In ensure, always print --- end ---

Use Integer(...) for parsing a and b, inside the same begin block, so non-integer input also lands in Bad operator (ArgumentError covers both).

For input 6 / * / 7, the output is:

6 * 7 = 42
--- end ---

For input 10 / / / 0:

Cannot divide by zero
--- end ---

Try it yourself

# TODO: define calc(a, op, b), raises ArgumentError on unknown op

raw_a = gets.chomp
op    = gets.chomp
raw_b = gets.chomp

# TODO: begin/rescue/ensure as described

All lessons in Logic & Flow