# Simple calculator in Ruby

I wrote a calculator in Ruby. These are the rules:

• Write the first number, in a new line the arithmetic operator, and in another line the last number.

• Use + for addition, - for subtraction, * for multiplication and / for division.

Implementation:

val1 = gets.to_i
sym = gets.chomp
val2 = gets.to_i

def addition(val1, val2)
return val1+val2
end

add = addition(val1, val2)

def subtraction(val1, val2)
return val1-val2
end

sub = subtraction(val1, val2)

def division(val1, val2)
return val1/val2
end

div = division(val1, val2)

def multiplication(val1, val2)
return val1*val2
end

mult = multiplication(val1, val2)

if sym == "+"
puts add
elsif sym == "-"
puts sub
elsif sym == "/"
puts div
elsif sym == "*"
puts mult
else puts "error"
end

• Welcome to Code Review. For the future, the title of a question should be a brief summary of the code. I changed it for you this time, feel free to further improve it if you want. To make the most out of your post, please read How to Ask. Aug 26, 2017 at 19:22
• Do you have anything particular you think needs improvement? What aspects are you looking for help with? Aug 26, 2017 at 22:36
• Well I know it works, but I would like to know if my code is functional, I wonder if there isn't an easier or better way of doing the same thing. And also I don't know how I could make it work on more than two numbers. Aug 27, 2017 at 3:40

## 2 Answers

Instead of calculating all the function returns and then checking which one the user input why not just run the function after checking the users input.

For example instead of

add = addition(val1, val2)
if sym == "+"
puts add


Why not

if sym == "+"
puts addition(val1, val2)

• It worked, thanks! It also solved the problem J H found. :) Aug 28, 2017 at 16:19

Suppose X is any val1 value, and 0 is supplied for val2. Then there are three classes of calculations that fail: X + 0, X - 0, X * 0. The difficulty is that you evaluate division(X, 0) when there is no need to do so, and you raise a div-by-zero exception.

You might put the four functions into a map, with +-*/ characters as the keys, and dispatch in that way, rather than using if statements.

• I hadn't noticed that, thanks.By map you mean the map method? I don't really know how to do that, I googled it but I couldn't understand it. Aug 27, 2017 at 16:57
• put four function objects into a dict
– J_H
Aug 28, 2017 at 1:25