Re: why, or when to, use a class method?



Thufir wrote:
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.

Why use a class method in the first example, though?

So that you can check whether a Song is too long without having to
create a SongList object:

#---------
class Song
attr_accessor :duration

def initialize(len)
@duration = len
end
end



class SongList
MaxTime = 5*60

def SongList.isTooLong(aSong)
return aSong.duration > MaxTime
end
end

#------------

s = Song.new(10)
puts SongList.isTooLong(s)

Otherwise, you would have to write:

s = Song.new(10)
sl = SongList.new()
puts sl.isTooLong(s)


Does that make sense for this example? Who knows.

--
Posted via http://www.ruby-forum.com/.

.