Created
March 31, 2012 03:11
-
-
Save guange2015/2258904 to your computer and use it in GitHub Desktop.
instance_exec vs class_exec
This file contains 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
# encoding: utf-8 | |
# different instance_exec whit class_exec | |
class O | |
def self.haha | |
puts 'haha' | |
end | |
end | |
O.instance_exec { | |
define_method(:hello) {p 'instance exec method'} | |
puts object_id # => O.object_id | |
puts haha # => success | |
} | |
O.class_exec { | |
define_method(:hello1) {p 'class_exec exec method'} | |
puts object_id # => O.object_id | |
puts haha # => success | |
} | |
O.new.hello # => success | |
O.new.hello1 # => success | |
# reciver both of self, so result is the same on message send. | |
# instance_exec runtime context is the self's engineclass. | |
# class_exec runtime context is the self. |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment