Skip to content

Instantly share code, notes, and snippets.

@laser
Last active January 3, 2016 19:48
Show Gist options
  • Save laser/8510398 to your computer and use it in GitHub Desktop.
Save laser/8510398 to your computer and use it in GitHub Desktop.
Calculators
class StatefulCalculator
def initialize
@total = 0
end
def add(x)
@total += x
self
end
def sub(x)
@total -= x
self
end
def mul(x)
@total *= x
self
end
def div(denom)
@total /= denom
self
end
def result
@total
end
end
# stateful
c = StatefulCalculator.new
assert_equal 3, c.add(1).add(5).div(2).result()
module StatelessCalculator
def add(x, y)
x + y
end
def sub(x, y)
x - y
end
def mul(x, y)
x * y
end
def div(num, denom)
num / denom
end
module_function :add, :sub, :mul, :div
end
# stateless
c = StatelessCalculator
assert_equal 3, c.div(c.add(1, 5), 2)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment