Skip to content

Instantly share code, notes, and snippets.

@nwjsmith
Created November 18, 2011 19:27
Show Gist options
  • Save nwjsmith/1377491 to your computer and use it in GitHub Desktop.
Save nwjsmith/1377491 to your computer and use it in GitHub Desktop.
# The following shows how to pass around methods in Ruby
# Unbound methods in Ruby suck, they can only be re-bound to objects that are
# a #kind_of? the original
class ReallyUnboundMethod
def initialize(name, body)
@name, @body = name, body
end
def bind(obj)
method_body = @body
evaluator = Proc.new do
obj.instance_eval &method_body
end
metaclass = class << obj; self; end
metaclass.send(:define_method, @name, evaluator)
end
end
class Method
def really_unbind
ReallyUnboundMethod.new(name, to_proc)
end
end
class You
def pronoun
"You"
end
def tomato(blah = nil)
p blah
pronoun + " say tomato"
end
end
class Me
def pronoun
"I"
end
end
you = You.new
me = Me.new
p you.tomato
you.method(:tomato).really_unbind.bind(me)
p me.tomato
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment