Skip to content

Instantly share code, notes, and snippets.

@guange2015
Created March 31, 2012 03:11
Show Gist options
  • Save guange2015/2258904 to your computer and use it in GitHub Desktop.
Save guange2015/2258904 to your computer and use it in GitHub Desktop.
instance_exec vs class_exec
# 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