Class Methods

Up to now we've been rather vaguely referring to the methods of classes, but we should start being more precise now. A class has two kinds of methods: instance methods and class methods. Most of the methods we've seen have been instance methods, because they are applied to objects, which are instances of a class. But one method we've used quite frequently is a class method. Think about what happens here:

x = Philosopher.new
x.allocate_chopsticks(2)

When we wrote a dining philosopher class back on Day 5, we defined allocate_chopsticks as an instance method, something that was to be applied to individual philosophers. new is also a method, but when it is called, its receiver is the Philosopher class itself, so new must be a class ...

Get Sams Teach Yourself Ruby in 21 Days now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.