Instance_eval vs. class_eval context

Is it the same context when a class is the receiver of instance_eval or
class_eval/module_eval?

···

--
Posted via http://www.ruby-forum.com/.

Is it the same context when a class is the receiver of instance_eval or
class_eval/module_eval?

No. In case of instance_eval you will be in the class, and in the
case of (class|module)_eval you will be in the class of the class
(which is Class) [Hurray for multiple meanings to a word!]

···

On 8/10/06, Andrew Gibson <gibson_andrew@yahoo.com> wrote:

Posted via http://www.ruby-forum.com/\.

--
"What is your function in life?" - Killer

No. In case of instance_eval you will be in the class, and in the
case of (class|module)_eval you will be in the class of the class
(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
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%

Guy Decoux

···

A::a

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

···

On Aug 11, 2006, at 11:14 AM, ts wrote:

> No. In case of instance_eval you will be in the class, and in the
> case of (class|module)_eval you will be in the class of the class
> (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%