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
-
1\$\begingroup\$ 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. \$\endgroup\$janos– janos2017年08月26日 19:22:06 +00:00Commented Aug 26, 2017 at 19:22
-
\$\begingroup\$ Do you have anything particular you think needs improvement? What aspects are you looking for help with? \$\endgroup\$Mark Thomas– Mark Thomas2017年08月26日 22:36:20 +00:00Commented Aug 26, 2017 at 22:36
-
\$\begingroup\$ 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. \$\endgroup\$Rocio– Rocio2017年08月27日 03:40:00 +00:00Commented Aug 27, 2017 at 3:40
2 Answers 2
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)
-
\$\begingroup\$ It worked, thanks! It also solved the problem J H found. :) \$\endgroup\$Rocio– Rocio2017年08月28日 16:19:17 +00:00Commented 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.
-
\$\begingroup\$ 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. \$\endgroup\$Rocio– Rocio2017年08月27日 16:57:09 +00:00Commented Aug 27, 2017 at 16:57
-
\$\begingroup\$ put four function objects into a dict \$\endgroup\$J_H– J_H2017年08月28日 01:25:31 +00:00Commented Aug 28, 2017 at 1:25