2008/3/7, Bharat Ruparel <bruparel / mercury.com>:
> Going through the Ruby Programming Language text Chapter 8 Reflection
>  and MetaProgramming.  Section 8.2.2 on page 270.
>
>  The following paragraph has me puzzled:
>
>  "Note the subtle but crucial difference between instance_eval and
>  class_eval when the code being evaluated contains a method definition.
>  instance_eval defines singleton methods of the object (and this results
>  in class methods when it is called on a class object).  class_eval
>  defines regular instance methods."
>
>  Is this not supposed to be the other way around?  instance_eval should
>  define instance methods and class_eval should define class methods.  Is
>  there a catch here?  Ruby is supposed to be following principle of least
>  surprise.  I must say I am surprised here, or there is something quite
>  profound that I don't get.

No, the book is correct. The "instance" in instance_eval indicates that you are
evaluating code in the context of one specific instance - if this
instance is a class
object, method definitions happen to define class methods.

instance_eval is defined in Object, so you can use it on any object - nothing
special about classes here, except that we call singleton methods on
classes "class methods".

class_eval evaluates code as if it appeared between "class ... end".
And a "def" between "class ... end" defines instance methods of the
class.

Stefan