Skip to content

Instantly share code, notes, and snippets.

@jasonayre
Created April 22, 2016 04:18
Show Gist options
  • Save jasonayre/2caef2c80814a00239b5efc7033d574d to your computer and use it in GitHub Desktop.
Save jasonayre/2caef2c80814a00239b5efc7033d574d to your computer and use it in GitHub Desktop.
Example of creaing an object oriented calculator in ruby
require 'rubygems'
require 'pry'
class Calculation
attr_reader :input
def initialize(*args)
@input = args
@result = calculate
end
def result
@result
end
end
class Add < Calculation
OPERAND = :+
def calculate
@input.reduce(&OPERAND)
end
end
# Add.new(1,2,3,4).result
# => 10
class Subtract < Calculation
OPERAND = :-
def calculate
@input.reduce(&OPERAND)
end
end
# Subtract.new(100, 10, 10).result
# => 80
class Divide < Calculation
OPERAND = :/
def calculate
@input.reduce(&OPERAND)
end
end
# Divide.new(100, 2, 2).result
# => 25
class Multiply < Calculation
OPERAND = :*
def calculate
@input.reduce(&OPERAND)
end
end
# Multiply.new(100, 2, 2).result
# => 400
# now we can define a calculator class to encapsulate the responsibility for performing
# the calculations, much like how a real calculator works
class Calculator
def initialize
clear!
end
def add(*args)
@calculations << Add.new(@result, *args)
@result = @calculations.last.result
self
end
def subtract(*args)
@calculations << Subtract.new(@result, *args)
@result = @calculations.last.result
self
end
def divide(*args)
@calculations << Divide.new(@result, *args)
@result = @calculations.last.result
self
end
def multiply(*args)
@calculations << Multiply.new(@result, *args)
@result = @calculations.last.result
self
end
def clear!
@calculations = []
@result = 0
end
def result
@result
end
def print!
@calculations.each do |calculation|
str = calculation.input.map(&:to_s).join(" #{calculation.class::OPERAND} ")
puts str
end
end
end
# screen = Calculator.new.add(1,2,3,4).add(1,2,3,4)
# screen.result
# => 20
# screen.multiply(2)
# => 40
# screen.multiply(2, 2)
# => 160
# screen.divide(16)
# => 10
#Now what if we want to see the trail of commands we have ran?
# 0 + 1 + 2 + 3 + 4
# 10 + 1 + 2 + 3 + 4
# 20 * 2 * 2
# 80 * 2
# 160 / 16
binding.pry
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment