What Are Class Methods For?

But why, you may reasonably ask, would you ever want to create a class method rather than the more usual instance method? There are two main reasons: First, a class method can be used as a “ready-to-run function” without having to go to the bother of creating an object just to use it, and second, it can be used on those occasions when you need to run a method before an object has been created.

For a few examples of using methods as “ready-to-run functions,” consider Ruby’s File class. Many of its methods are class methods. This is because most of the time you will be using them to do something to, or return information about, an existing file. You don’t need to create a new File object to do that; instead, you pass the filename as an argument to the File class methods. You’ll look more closely at the File class in Chapter 13. Here are examples of a few of its class methods in use:

file_methods.rb

fn = 'file_methods.rb'
if File.exist?(fn) then
   puts(File.expand_path(fn))
   puts(File.basename(fn))
   puts(File.dirname(fn))
   puts(File.extname(fn))
   puts(File.mtime(fn))
   puts("#{File.size(fn)} bytes")
else
   puts( "Can't find file!")
end

This outputs something like this:

C:/bookofruby2/ch7/file_methods.rb
file_methods.rb
.
.rb
2010-10-05 16:14:53 +0100
300 bytes

The other occasion when a class method is vital is when you need to use a method before an object has been created. The most important example of this is the new method.

You call the new method every time you create an object. Until the object has been created, you clearly cannot call one of its instance methods—because you can call instance methods only from an object that already exists. When you use new, you are calling a method of the class itself and telling the class to create a new instance of itself.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.191.54.245