Skip to content

Instantly share code, notes, and snippets.

@laser
Last active January 3, 2016 17:09
Show Gist options
  • Save laser/8493929 to your computer and use it in GitHub Desktop.
Save laser/8493929 to your computer and use it in GitHub Desktop.
Simple 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 = @total / denom
self
end
def result
@total
end
end
# stateful
c = StatefulCalculator.new
assert_equal 3, c.add(1).add(5).divide(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, :p
end
# stateless
c = StatelessCalculator
assert_equal 3, c.divide(c.add(1, 5), 2)
@coopernurse
Copy link

module Calc

    def add(x,y,*filters)
        run_filters(x,y,x+y,filters)
    end

    def subtr(x,y,*filters)
        run_filters(x,y,x-y,filters)
    end

    def run_filters(x,y,res,filters)
        filters.each do |fx|
            fx.call(x,y,res)
        end
        res
    end

    module_function :add, :subtr

end

class CalcLazy

    def initialize(initial=0)
        @initial = initial
        @fxs = []
    end

    def add(y)
        @fxs.push(lambda{|acc| acc+y})
        self
    end

    def subtr(y)
        @fxs.push(lambda{|acc| acc-y})
        self
    end

    def total(*filters)
        acc = @initial
        @fxs.each do |fx|
            acc = fx.call(acc)
            filters.each do |filt|
                filt.call(acc)
            end
        end
        acc
    end

end

##############################

include Calc

puts "No filter:"
puts add(3, 2)
puts

print_filter = lambda{|x,y,res| puts "print_filter here: #{res}" }

puts "With print_filter:"
puts add(3, 2, print_filter)
puts

puts "No filter:"
puts CalcLazy.new(3).add(2).total()
puts

print_filter2 = lambda{|res| puts "print_filter2 here: #{res}" }

puts "No filter:"
puts CalcLazy.new(3).add(2).total(print_filter2)
puts

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment