Follow Techotopia on Twitter

On-line Guides
All Guides
eBook Store
iOS / Android
Linux for Beginners
Office Productivity
Linux Installation
Linux Security
Linux Utilities
Linux Virtualization
Linux Kernel
System/Network Admin
Scripting Languages
Development Tools
Web Development
GUI Toolkits/Desktop
Mail Systems
Eclipse Documentation

How To Guides
General System Admin
Linux Security
Linux Filesystems
Web Servers
Graphics & Desktop
PC Hardware
Problem Solutions
Privacy Policy




Ruby Programming
Previous Page Home Next Page

Class Methods

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.

aSong =

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.


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


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
song1 ="Bicylops", "Fleck", 260)
SongList.isTooLong(song1) false
song2 ="The Calling", "Santana", 468)
SongList.isTooLong(song2) true

Ruby Programming
Previous Page Home Next Page

  Published under the terms of the Open Publication License Design by Interspire