Skip to content

Instantly share code, notes, and snippets.

@ernie
Created September 6, 2011 14:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ernie/1197634 to your computer and use it in GitHub Desktop.
Save ernie/1197634 to your computer and use it in GitHub Desktop.
instance_exec LIES!!!
#!/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>
@ernie
Copy link
Author

ernie commented Sep 6, 2011

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. :(

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