Created
September 6, 2011 14:11
-
-
Save ernie/1197634 to your computer and use it in GitHub Desktop.
instance_exec LIES!!!
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
#!/usr/bin/env ruby | |
# http://www.ruby-doc.org/core-1.8.7/classes/Object.html#M000006 : | |
# | |
# obj.instance_exec(arg...) {|var...| block } => obj | |
# | |
# Executes the given block within the context of the receiver (obj). | |
# In order to set the context, the variable self is set to obj while | |
# the code is executing, giving the code access to obj‘s instance variables. | |
# Arguments are passed as block parameters. | |
class Classy | |
def self.foo | |
puts self | |
end | |
def bar | |
puts self | |
end | |
end | |
class Executioner | |
def exec(&block) | |
instance_exec &block | |
end | |
end | |
exe = Executioner.new # => #<Executioner:0x007f8cb884d108> | |
exe.exec { puts self } # => #<Executioner:0x007f8cb884d108> | |
exe.exec &lambda { puts self } # => #<Executioner:0x007f8cb884d108> | |
exe.exec &Classy.method(:foo) # => Classy | |
exe.exec &Classy.new.method(:bar) # => #<Classy:0x007f8cb884ce10> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
So, I understand there are various reasons why a method object would want/need to hang onto its own binding even when asked to do otherwise, but I have to admit I was surprised and disappointed at these results. :(