# Calculator in Ruby

I have created a calculator in Ruby. I am using Ruby 2.1.0. I'm fairly sure that someone will be able to improve this, as I am quite new to Ruby.

puts "Welcome to Calc"
puts ""

puts "Please enter the first number"
n1 = gets.to_i()
puts ""

puts "Please enter the second number"
n2 = gets.to_i()
puts ""

subtract = n1 - n2
multiply = n1 * n2
divide = n1 / n2
power = n1 ** n2
sqrt1 = Math.sqrt(n1)
sqrt2 = Math.sqrt(n2)

puts "#{n1} + #{n2} = #{add}"
puts "#{n1} - #{n2} = #{subtract}"
puts "#{n1} * #{n2} = #{multiply}"
puts "#{n1} / #{n2} = #{divide}"
puts "#{n1} ** #{n2} = #{power}"
puts "#{n1} √ = #{sqrt1}"
puts "#{n2} √ = #{sqrt2}"

gets()


One thing you forgot to check was if n2 is 0 and n1 is non zero, in which case the answer is either undefined or a signed infinity.

In any case, in the current version, it will just output a divide by zero error with a stack trace, which isn't very user friendly. I would advise changing the message by catching the error and putting something else.

• Thanks. This was useful. It is now set so that before running the code on line 12 and onwards, it checks the numbers, using 'if n1 != 0 and n2 == 0'. And outputs an error message if they are. – user69731 Apr 6 '15 at 17:20
• In addition: divide on integers is a modulo division. If it is intented to use the modulo division, then I would expect both values using divmod. Or you have to convert one value to float value. – knut Apr 6 '15 at 18:02

You are doing integer division, which is probably not the expected behaviour for a calculator. For that matter, it makes little sense to restrict the inputs to integers, as most calculators are able to handle arbitrary decimal values.