A
Andrew Gibson
Is it the same context when a class is the receiver of instance_eval or
class_eval/module_eval?
class_eval/module_eval?
Is it the same context when a class is the receiver of instance_eval or
class_eval/module_eval?
A> No. In case of instance_eval you will be in the class, and in the
A> case of (class|module)_eval you will be in the class of the class
A> (which is Class) [Hurray for multiple meanings to a word!]
no, not really. ruby use self and internally ruby_class which give it
where it can define method when it find keyword like 'def',
'alias', ...
With obj.instance_eval ruby will make
* self = obj , ruby_class = obj singleton class
This mean that inside instance_eval it will define singleton method
#instance_eval work with any object, but a class is a little special
because it can be seen as an object or as a class. This is why
#module_eval, #class_eval exist.
With obj.class_eval ruby will make
* self = obj, ruby_class = obj
This mean that inside class_eval ruby will define instance method.
One way to see it
moulon% ruby -e 'class A; end; A.instance_eval{ p self; def a()
puts "A::a" end}; A.a'
A
A::a
moulon%
moulon% ruby -e 'class A; end; A.class_eval{ p self; def a() puts
"A#a" end}; A.new.a'
A
A#a
moulon%
Want to reply to this thread or ask your own question?
You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.