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 ""

add = n1 + n2
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}"


2 Answers 2


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.

  • \$\begingroup\$ 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. \$\endgroup\$
    – user69731
    Apr 6, 2015 at 17:20
  • \$\begingroup\$ 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. \$\endgroup\$
    – knut
    Apr 6, 2015 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.


Your Answer

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