Last active
January 3, 2016 17:09
-
-
Save laser/8493929 to your computer and use it in GitHub Desktop.
Simple Calculators
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 = @total / denom | |
self | |
end | |
def result | |
@total | |
end | |
end | |
# stateful | |
c = StatefulCalculator.new | |
assert_equal 3, c.add(1).add(5).divide(2).result() |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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, :p | |
end | |
# stateless | |
c = StatelessCalculator | |
assert_equal 3, c.divide(c.add(1, 5), 2) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
TBD |
coopernurse
commented
Jan 18, 2014
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment