0
\$\begingroup\$

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 
\$\endgroup\$
3
  • 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
    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\$ 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
    Aug 27, 2017 at 3:40

2 Answers 2

1
\$\begingroup\$

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)
\$\endgroup\$
1
  • \$\begingroup\$ It worked, thanks! It also solved the problem J H found. :) \$\endgroup\$
    – Rocio
    Aug 28, 2017 at 16:19
0
\$\begingroup\$

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.

\$\endgroup\$
2
  • \$\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
    Aug 27, 2017 at 16:57
  • \$\begingroup\$ put four function objects into a dict \$\endgroup\$
    – J_H
    Aug 28, 2017 at 1:25

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.