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?

On 8/10/06, Andrew G. [email protected] wrote:

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!]

“A” == Arnaud B. [email protected] 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%

Guy Decoux

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

With obj.instance_eval ruby will make

  • self = obj, ruby_class = obj

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 G. II

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs