James Gray
8/11/2006 4:48:00 PM
On Aug 11, 2006, at 11:14 AM, ts wrote:
>>>>>> "A" == Arnaud Bergeron <abergeron@gmail.com> writes:
>
> 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%
I've always had trouble understanding this and for some reason this
is the email that finally clicked all the pieces into place for me.
Thanks Guy!
James Edward Gray II