Skip to content
Tutorials Center
My learning

Topics

Lesson 50 of 134 ยท Object-Oriented Ruby

Instance and Class Methods

Understand Ruby instance methods versus class methods - what self means, def self.method, class << self, class instance variables, and why class variables (@@) are risky.

In Classes and Objects every method you wrote worked on one object: rex.describe, acct.deposit(50). These are instance methods. They read and change the instance variables of the object they were called on. But some behaviour does not belong to any single object. How many dogs exist? How do I build a dog from the text "Rex,3"? What is the standard tax rate for all orders? Such behaviour belongs to the class itself, and Ruby calls those class methods.

To understand the difference properly you need one key idea: self. Ruby always keeps track of the "current object", and self is its name. Once you know what self is at each point of a program, class methods, class instance variables and the infamous @@ variables all stop being mysterious. This lesson explains them, shows the common patterns (factory methods, counters, registries), and warns about the one Ruby feature that experienced developers avoid, the class variable.

What is self?

self is the object that receives the current method call. Inside an instance method it is the instance. Directly inside a class body, it is the class itself. At the top level of your script it is a special object called main.

Ruby self in three places

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

The class body is ordinary running code. Ruby executes the puts inside class Robot while it builds the class, which is why you see that line before anything else from the Robot section. And when you call a method, self inside it is whatever stands to the left of the dot: Robot.whoami runs with self set to the class, Robot.new.whoami with self set to the new instance.

Defining class methods

A class method is defined by naming its owner: def self.name. Because self in a class body is the class, this means "define the method on this class object". You call it on the class, not on an instance.

Ruby Class methods and factory methods

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

from_fahrenheit is a factory method: an alternative way to build an object, with a descriptive name. Ruby classes have only one initialize, so factories are how you offer several ways to construct the same thing (from_fahrenheit, parse, from_json, default). Note the call to plain new inside the class method: self is the class, so new(...) means self.new(...). Using new rather than Temperature.new also keeps subclasses working, because self will be the subclass when it calls the factory.

Mixing the two levels up gives a clear error:

Ruby Calling a class method on an instance (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

The output starts with Pizza, then Ruby stops with main.rb:10:in '<main>': undefined method 'margherita' for an instance of Pizza (NoMethodError). The method exists, but on the class object, not on the instances. The reverse (calling an instance method on the class, Pizza.size) fails the same way.

class << self

When a class has several class methods you can group them. class << self opens the class's "singleton" scope (explained in Singleton Methods and the Singleton Class), and every def inside becomes a class method. The two spellings produce identical methods.

Ruby Two ways to define class methods

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

class << self has one practical advantage: a bare private inside it makes the following class methods private, which a plain private in the class body would not do. Also see how the error reads private method 'secret' called for class Geometry. The word class replaces "an instance of" because the receiver is the class itself.

For a single class method, def self.name is clearer. Use class << self when you have a block of related class methods, or need private or attr_accessor at class level.

Class-level state: class instance variables

Classes are objects, and objects can have instance variables. An @variable set where self is the class is a class instance variable: one value per class, shared by all instances of it because they all reach it through the class.

Ruby Counting instances with a class instance variable

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

@issued = 0 in the class body sets up the counter, and the class methods read and update it. The instances reach it by calling self.class.next_number, because an instance's own @issued would be a different, separate variable (an instance has no access to the class's). The last two lines make this visible: the tickets carry @number, while Ticket itself carries @issued.

Class variables (@@) and why to avoid them

Ruby also has class variables, written @@name. They look like what you want for "shared by everything in this class", and they are shared. The problem is that they are shared with all subclasses too, and across reopenings of the class, with no isolation.

Ruby The class variable trap

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

Resetting the subclass silently changed the parent's counter to 100: there is only one @@count, shared by the whole family. With class instance variables each class would have its own value: SpecialCounter would start at nil and leave Counter alone. Class variables are also hard to reason about because lookup depends on where the code is written, so many style guides say to avoid them, and replace them with class instance variables (as in Ticket), constants for fixed values, or a dedicated object.

There is a second sharp edge: reading a class variable that was never set raises an error instead of returning nil (unlike an ordinary instance variable):

Ruby Uninitialized class variable (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

The message is main.rb:3:in 'Settings.level': uninitialized class variable @@level in Settings (NameError). Note the method name in the trace: class methods are shown as Settings.level, instance methods as Settings#level. That notation is also how Ruby documentation names methods.

Constants and class methods together

For values that never change (a tax rate, a list of valid states) a constant is simpler and safer than any variable. A class method can expose it, validate against it, or compute from it.

Ruby Constants and a registry

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

The registry records every shape built through the factory. SIDES is frozen so no outside code can add to it by accident (see Immutability and freeze). Because build validates before it stores anything, a failed call leaves the registry untouched: it still has 2 entries at the end.

Which kind of method should it be?

Ask: does this need data from one particular object?

Question Answer Kind
Reads or changes an object's own state yes instance method
Builds objects in a new way yes class method (factory)
Works without any object (pure helper, lookup) yes class method
Keeps a count or list for the whole class yes class method with a class instance variable

Do not turn a class into a bag of unrelated class methods only to avoid creating objects. A class with only class methods is usually better as a module (see Modules and Mixins), which cannot be instantiated and says so.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What is self directly inside a class Robot ... end body (not inside a method)?

    The class body runs with self set to the class object. That is why def self.name defines a method on the class.
  2. 2. Given class Pizza; def self.margherita; new; end; end, what does Pizza.new.margherita do?

    Class methods are called on the class. Instances do not have them.
  3. 3. What is the main danger of @@count in a class with subclasses?

    A class variable has one value for the class and every subclass, which leads to surprising interference. Class instance variables are per class.
  4. 4. What does reading an unassigned class variable (@@x) do?

    Unlike instance variables, class variables raise NameError when read before assignment.
  5. 5. Why use new instead of Temperature.new inside a factory class method?

    Inside a class method self is the class that received the call, which may be a subclass. Calling new builds an instance of that class.

Summary

  • Instance methods work on one object; class methods belong to the class object itself and are called on it.
  • self is the receiver of the current call: the instance in instance methods, the class in the class body and in class methods.
  • Define class methods with def self.name or group them in class << self (where private and attr_* also work at class level).
  • Factory methods give a class several named ways to build objects; call new (not the class name) so subclasses keep working.
  • A class instance variable (@x set at class level) is per class and the safe way to keep class-wide state.
  • Class variables (@@x) are shared with subclasses, raise NameError when unset, and are best avoided.

Next: Inheritance