Skip to content

Instantly share code, notes, and snippets.

@mike-burns
Created October 26, 2012 13:20
Show Gist options
  • Save mike-burns/3958781 to your computer and use it in GitHub Desktop.
Save mike-burns/3958781 to your computer and use it in GitHub Desktop.
refinements cannot do recursion
class Literal < Struct.new(:number)
def show
print number
end
end
class Add < Struct.new(:a, :b)
def show
a.show
print ' + '
b.show
end
end
module Evalution
refine Literal do
def eval
number
end
end
refine Add do
def eval
a.eval + b.eval
end
end
end
def run1
using Evalution
Add.new(Literal.new(3), Literal.new(4)).show
puts
p Add.new(Literal.new(3), Literal.new(4)).eval
end
run1
class Negate < Struct.new(:expression)
def show
print '- ('
expression.show
print ')'
end
end
module NegativeEvaluation
refine Negate do
def eval
- expression.eval
end
end
end
def run2
using Evalution
using NegativeEvaluation
Add.new(Literal.new(5), Negate.new(Add.new(Literal.new(2), Literal.new(2)))).show
puts
p Add.new(Literal.new(5), Negate.new(Add.new(Literal.new(2), Literal.new(2)))).eval
end
run2
@mike-burns
Copy link
Author

3 + 4
7
5 + - (2 + 2)
refinements.rb:24:in `eval': private method `eval' called for #<Negate:0x000000021009a8> (NoMethodError)
    from refinements.rb:60:in `run2'
    from refinements.rb:62:in `<main>'

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