Hey guys, I was just playing around with ruby bindings this morning and came up with something very interesting:
class Pink
attr_reader :color
def initialize
@color = "pink"
end
def pink?
@color == "pink"
end
end
class Blue
def color
"blue"
end
def import_method(name, other_object)
(class << self; self end).send(:define_method, name, other_object.method(name).to_proc)
end
end
# This produces very interesting results:
blue = Blue.new
pink = Pink.new
blue.import_method(:pink?, pink)
blue.color #=> "blue"
blue.pink? #=> true
What's happening is that (using a bit of black magic) the method "pink?" on the blue instance remains bound to the pink instance, so when you run blue.pink?, the result is that inside the "pink?" method, self is not blue, but pink!
Have fun with this! :)
- daniel parker -
"You have granted me life and steadfast love, and your care has preserved my spirit." Job 10:12
"The LORD is my chosen portion and my cup . . . indeed, I have a beautiful inheritance." Psalm 16:5-6
"Give what you can ... take nothing back!"