calculator in ruby

Interactive Ruby-Style Calculator

Use this calculator to test operations you would commonly implement in a Ruby command-line app.

Result will appear here.
Equivalent Ruby Code
a = 10
b = 5
result = a + b
puts "Result: #{result}"
Calculation History
  • No calculations yet.

If you searched for calculator in ruby, you are probably building one of your first practical Ruby scripts. Great choice. A calculator project teaches variables, methods, user input, flow control, and error handling in one small app.

Why Build a Calculator in Ruby?

A calculator is simple enough to finish quickly, but rich enough to reinforce fundamentals you'll use in larger projects. In one mini-project you can practice:

  • Reading input from users with gets
  • Converting text to numbers with to_i and to_f
  • Using conditionals and case statements
  • Defining reusable methods
  • Handling invalid input cleanly

That combination makes it one of the best beginner-friendly Ruby exercises.

Step 1: Start with Basic Input

Every command-line calculator begins with collecting two numbers and an operator. Keep the first version tiny and working:

print "Enter first number: "
a = gets.chomp.to_f

print "Enter operator (+, -, *, /): "
op = gets.chomp

print "Enter second number: "
b = gets.chomp.to_f

Why to_f and Not to_i?

to_f supports decimals, so your calculator can handle values like 3.75. If you use to_i, Ruby will truncate decimal input and you may get unexpected results.

Step 2: Add Calculation Logic with case

Ruby’s case statement is perfect for mapping operators to actions:

result =
  case op
  when "+"
    a + b
  when "-"
    a - b
  when "*"
    a * b
  when "/"
    if b == 0
      "Error: Cannot divide by zero."
    else
      a / b
    end
  else
    "Error: Invalid operator."
  end

puts "Result: #{result}"

Important Validation Rule

Never skip divide-by-zero checks. They prevent crashes and teach defensive programming, which is essential in production software.

Complete Beginner Ruby Calculator Script

Here is a clean, single-file version you can run immediately:

def calculate(a, op, b)
  case op
  when "+"
    a + b
  when "-"
    a - b
  when "*"
    a * b
  when "/"
    return "Error: Cannot divide by zero." if b == 0
    a / b
  when "%"
    return "Error: Cannot modulo by zero." if b == 0
    a % b
  when "**"
    a ** b
  else
    "Error: Invalid operator."
  end
end

print "First number: "
a = gets.chomp.to_f

print "Operator (+, -, *, /, %, **): "
op = gets.chomp

print "Second number: "
b = gets.chomp.to_f

puts "Result: #{calculate(a, op, b)}"

Make It Better: Loop Until User Exits

Most real calculators keep running. You can wrap the flow in a loop and ask if the user wants another calculation:

loop do
  print "First number: "
  a = gets.chomp.to_f

  print "Operator (+, -, *, /, %, **): "
  op = gets.chomp

  print "Second number: "
  b = gets.chomp.to_f

  puts "Result: #{calculate(a, op, b)}"

  print "Again? (y/n): "
  break unless gets.chomp.downcase == "y"
end

Object-Oriented Ruby Calculator

As your app grows, put logic inside a class. This keeps code organized and easier to test.

class Calculator
  def calculate(a, op, b)
    case op
    when "+" then a + b
    when "-" then a - b
    when "*" then a * b
    when "/"
      raise ArgumentError, "Cannot divide by zero" if b == 0
      a / b
    else
      raise ArgumentError, "Unsupported operator: #{op}"
    end
  end
end

calc = Calculator.new
puts calc.calculate(12, "*", 4) # => 48

Benefits of This Approach

  • Cleaner separation of user interface and calculation logic
  • Easier unit testing
  • Simpler extension for scientific or financial operations

Testing Your Ruby Calculator

Even a tiny calculator should have tests. With minitest:

require "minitest/autorun"
require_relative "calculator"

class CalculatorTest < Minitest::Test
  def setup
    @calc = Calculator.new
  end

  def test_addition
    assert_equal 7, @calc.calculate(3, "+", 4)
  end

  def test_divide_by_zero
    assert_raises(ArgumentError) { @calc.calculate(10, "/", 0) }
  end
end

Common Mistakes Beginners Make

  • Forgetting type conversion: gets returns strings, not numbers.
  • Not validating operators: always handle unknown input.
  • Ignoring edge cases: division/modulo by zero must be caught.
  • Mixing UI and logic: prefer methods/classes for calculation code.

What to Build Next

After the basic Ruby calculator works, add one feature at a time:

  • Square root, logarithm, and trigonometric functions
  • Memory store/recall commands
  • Expression parsing (e.g., (2 + 3) * 4)
  • A Sinatra or Rails web interface for the same calculator core

Final Thoughts

A calculator in Ruby is a small project with huge teaching value. You will learn data types, control flow, methods, classes, and testing—all without overwhelming complexity. Start simple, make it correct, then make it elegant. If you can build and improve this project, you are already thinking like a software developer.

🔗 Related Calculators