Skip to content

Instantly share code, notes, and snippets.

@ernie ernie/lies.rb
Created Sep 6, 2011

Embed
What would you like to do?
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

This comment has been minimized.

Copy link
Owner Author

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
You can’t perform that action at this time.