Created
November 18, 2011 16:25
-
-
Save nwjsmith/1376947 to your computer and use it in GitHub Desktop.
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
# The following shows how to pass around methods in Ruby | |
class ReallyUnboundMethod | |
def initialize(name, body) | |
@name, @body = name, body | |
end | |
def bind(obj) | |
metaclass = class << obj; self; end | |
metaclass.send(:define_method, @name, &@body) | |
end | |
end | |
class Method | |
def really_unbind | |
ReallyUnboundMethod.new(name, to_proc) | |
end | |
end | |
class You | |
def pronoun | |
"You" | |
end | |
def tomato | |
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