From: Todd Benson Date: 2008-03-08T05:20:08+09:00 Subject: Re: instance_eval and class_eval - names got mixed up? On Fri, Mar 7, 2008 at 2:06 PM, Bharat Ruparel wrote: > 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. > > Bharat It's the use of the word "instance" here that causes the problem. Singleton methods are specific to a single instance of an object. An instance method refers to a method that's available to _every_ instance of a class upon their creation. Maybe it should be singleton_eval and instance_eval, but, see, that doesn't really make sense, because that would imply eval being used within the singleton class of the object. One of those meta-programming language work-arounds I guess. Todd