From: Thufir Date: 2007-11-01T05:27:43+09:00 Subject: why, or when to, use a class method? Here's the example: Jukeboxes charge money for each song played, not by the minute. That makes short songs more profitable than long ones. We may want to prevent songs that take too long from being available on the SongList. We could define a class method in SongList that checked to see if a particular song exceeded the limit. We'll set this limit using a class constant, which is simply a constant (remember constants? they start with an uppercase letter) that is initialized in the class body. class SongList MaxTime = 5*60 # 5 minutes def SongList.isTooLong(aSong) return aSong.duration > MaxTime end end song1 = Song.new("Bicylops", "Fleck", 260) SongList.isTooLong(song1) » false song2 = Song.new("The Calling", "Santana", 468) SongList.isTooLong(song2) » true 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. 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. The class variable makes more sense to me, I can see the need better: "For example, our jukebox may want to record how many times each particular song has been played. This count would probably be an instance variable of the Song object. When a song is played, the value in the instance is incremented. But say we also want to know how many songs have been played in total. We could do this by searching for all the Song objects and adding up their counts, or we could risk excommunication from the Church of Good Design and use a global variable. Instead, we'll use a class variable. class Song @@plays = 0 def initialize(name, artist, duration) @name = name @artist = artist @duration = duration @plays = 0 end def play @plays += 1 @@plays += 1 "This song: #@plays plays. Total #@@plays plays." end end" 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? thanks, Thufir