You’ve used numerous methods throughout this book. On the whole, they aren’t particularly complicated things, so you may wonder why this chapter, which is all about methods, is so long. As you will discover, there is much more to methods than meets the eye.
The methods you’ve been using so far have been instance methods. An instance method belongs to a specific instance of a class—in other words, to an individual object. It is also possible to write class methods. (Some other languages refer to this kind of method as a static method.) A class method belongs to the class itself. To define a class method, you must precede the method name with the class name and a full stop.
class MyClass def MyClass.classMethod puts( "This is a class method" ) end def instanceMethod puts( "This is an instance method" ) en end
You should use the class name when calling a class method:
MyClass.classMethod
A specific object cannot call a class method. Nor can a class call an instance method:
MyClass.instanceMethod #=> Error! This is an 'undefined method' ob.classMethod #=> Error! This is an 'undefined method'