Sometimes a class needs to provide methods that work without being tied
to any particular object.
We've already come across one such method.
The
new
method creates a new
Song
object but is not
itself associated with a particular song.
You'll find class methods sprinkled throughout the Ruby libraries. For
example, objects of class
File
represent open files
in the underlying file system. However, class
File
also provides
several class methods for manipulating files that aren't open and
therefore don't have a
File
object. If you want to delete a file,
you call the class method
File.delete
, passing in the name.
File.delete("doomedFile")
|
Class methods are distinguished from instance methods by their
definition.
Class methods are defined by placing the class name and a period in
front of the method name.
class Example
def instMeth # instance method
end
def Example.classMeth # class method
end
end
|
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
|