ruby eval magic

D

DMG

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

Thanks,
Dawid
 
D

dmg2009

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
 
B

Brian Candler

unknown said:
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.
 
D

dmg2009

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)

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

Ask a Question

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.

Ask a Question

Similar Threads


Members online

No members online now.

Forum statistics

Threads
473,744
Messages
2,569,483
Members
44,901
Latest member
Noble71S45

Latest Threads

Top