From: Brian Candler Date: 2009-12-14T19:51:13+09:00 Subject: Re: ruby eval magic 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. -- Posted via http://www.ruby-forum.com/.