From: "David A. Black" Date: 2007-11-01T05:41:24+09:00 Subject: Re: why, or when to, use a class method? Hi -- On Thu, 1 Nov 2007, Thufir wrote: > Because the definition is declared with "def > SongList.isTooLong(aSong)", this indicates it to be a class variable > for the SongList class, ok so far. It declares it to be a class *method*. It may or may not use a class variable (actually the example you gave does not). > Why a class variable? All > SongList objects will use the same method, but wouldn't they use the > same method even if it were an instance method? Methods are declared > on the class, not the instance. > > There is one @plays per instance, but only one @@plays which all Song > objects share; this I follow. > > Why use a class method in the first example, though? Typically, a class method is used when you have a method that's directly related to the objects you're using the class to represent, but that does something at a more general level than a specific object. For example, let's say you have a Car class. You want to create individual cars: c = Car.new and do things with them: c.fill_with_fuel c.drive(120) However, you might also want to do things at a more general level that still have to do with cars. For example: class Car def self.brands ["Ford", "Honda", "Toyota", "Volvo" ...] end end This provides a list of all car brands. I've made it a class method because while every individual car may be of a particular brand, I don't expect every car to know about every brand. The Car class, however, is a good place to put general, high-level information about cars, like a list of all brands. David -- Upcoming training by David A. Black/Ruby Power and Light, LLC: * Advancing With Rails, Edison, NJ, November 6-9 * Advancing With Rails, Berlin, Germany, November 19-22 * Intro to Rails, London, UK, December 3-6 (by Skills Matter) See http://www.rubypal.com for details!