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
MediumDefine a method calc(a, op, b) that:
- Raises
ArgumentErrorwith message"unknown operator"ifopis 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, printBad operator - On
ZeroDivisionError, printCannot 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
1Strings In Depth
String Methods OverviewString InterpolationIterating Over StringsSplit and JoinRecap - String Weaver4Blocks, Procs & Lambdas
What is a Block?do..end vs BracesThe yield KeywordBlock ParametersProcs and LambdasRecap - Custom Iterator7Hashes Part 2
Hash.new with DefaultsIterating HashesNested HashesMerging and TransformingRecap - Frequency Counter10Project - Student Records
Project OverviewAdd Student5Enumerable Powerhouse
Select and RejectChaining MapReduce / Injectcount, all?, any?, none?group_by and partitionsort_by, min_by, max_byRecap - Data Pipeline8Advanced Decision Making
Case with Classes & RegexMulti-value whenTernary OperatorInline if / unlessRecap - Grade Classifier32D Arrays
2D Array BasicsAccessing 2D ElementsIterating Over 2D ArraysCommon 2D PatternsRecap - Matrix Operations9Error Handling
What is an Exception?begin / rescueMultiple rescue Clausesensure and raiseRecap - Safe Calculator