Ruby eval magic

Can anybody explain me, why this is true:
self.class.class_eval{self} == self.class.instance_eval{self}

Thanks,
Dawid

On Dec 14, 10:33 am, DMG [email protected] wrote:

Can anybody explain me, why this is true:
self.class.class_eval{self} == self.class.instance_eval{self}

Thanks,
Dawid

It seems that we don’t need class_eval method. Because if we use a
Module or Class directly, we can use:
SomeClass.instance_eval { … }

and if we have an object and we need to work on its class, we can use:
some_object.class.instance_eval { … }

So, do we need class_eval/module_eval?

Thanks,
Dawid

unknown wrote:

It seems that we don’t need class_eval method. Because if we use a
Module or Class directly, we can use:
SomeClass.instance_eval { … }

and if we have an object and we need to work on its class, we can use:
some_object.class.instance_eval { … }

So, do we need class_eval/module_eval?

Yes, we do. But it took me a while until I found out why.

When Ruby code is executing, there are two bits of state which are
maintained:

  • the current object, which is exposed as ‘self’
  • the current class, where instance methods are defined. This is pretty
    well hidden, but sometimes it matters.

Try the following code:

class Foo; end

Foo.class_eval "def bar; puts 'Hello!'; end"

Foo.new.bar

If you change class_eval to instance_eval, it won’t work as shown. In
fact you’ll make a class method on Foo (Foo.bar)

AFAIK, class_eval and module_eval are the same thing though.

On Dec 14, 11:51 am, Brian C. [email protected] wrote:

Foo.class_eval "def bar; puts 'Hello!'; end"

Foo.new.bar

If you change class_eval to instance_eval, it won’t work as shown. In
fact you’ll make a class method on Foo (Foo.bar)

Oh, I see. Yes, the context matter when defining methods.
Thank you very much!