TExcelTAD
Home › Ruby › Ruby Class Methods & self

Ruby Class Methods & self

So far all our methods were instance methods: you call them on an object (dog.bark). A class method is called on the class itself (Dog.create). To understand class methods you need to understand self — the object Ruby is "inside" at any moment.

What is self?

self always refers to the current object. Its value depends on where the code is:

ruby · try it yourself
p self

class Robot
  p self                 # inside the class body: the class

  def whoami
    self                 # inside an instance method: the object
  end
end

r = Robot.new
p r.whoami.equal?(r)
p r.whoami.class
main
Robot
true
Robot
Where self is
Top level of a file main (an Object)
Inside class Foo ... end (not in a method) the class Foo
Inside an instance method the object the method was called on
Inside a class method (def self.x) the class

Defining class methods with def self.

Since self in the class body is the class, def self.name defines a method on the class:

ruby · try it yourself
class Temperature
  attr_reader :celsius

  def initialize(celsius)
    @celsius = celsius
  end

  def self.from_fahrenheit(f)
    new((f - 32) * 5 / 9.0)
  end

  def self.freezing = new(0)

  def to_s = "#{celsius.round(1)}°C"
end

puts Temperature.from_fahrenheit(98.6)
puts Temperature.freezing
puts Temperature.new(25)
37.0°C
0°C
25°C

Class methods that build objects in different ways, like from_fahrenheit, are called factory methods. Inside them, new means self.new — the class's own constructor.

The class << self block

When a class has many class methods, you can group them in a class << self block. Every def inside defines a class method:

ruby · try it yourself
class Slug
  class << self
    def from(title)
      clean(title).split.join("-")
    end

    private

    def clean(text)
      text.downcase.gsub(/[^a-z0-9 ]/, "")
    end
  end
end

p Slug.from("Ruby 3.4: What's New?")

begin
  Slug.clean("x")
rescue NoMethodError => e
  puts "clean is private"
end
"ruby-34-whats-new"
clean is private

Class-level state

Data that belongs to the class as a whole (not to one instance) can live in a class instance variable — an @variable set on the class itself:

ruby · try it yourself
class User
  @count = 0

  class << self
    attr_reader :count

    def create(name)
      @count += 1
      new(name)
    end
  end

  attr_reader :name

  def initialize(name) = @name = name
end

User.create("ana")
User.create("bo")
p User.count
2

There are also class variables with two @@ signs. They are shared between a class and all its subclasses, which often surprises people:

ruby · try it yourself
class Base
  @@registry = []
  def self.register(x) = @@registry << x
  def self.registry = @@registry
end

class Plugin < Base; end

Plugin.register(:csv)
Base.register(:json)
p Base.registry
p Plugin.registry
[:csv, :json]
[:csv, :json]

Tip: Prefer class instance variables (@count on the class) over @@class_variables unless you specifically want subclasses to share the same storage.

Constants on classes

Constants defined in a class are reached from outside with :::

ruby · try it yourself
class Pizza
  SIZES = {small: 25, medium: 30, large: 35}.freeze
  BASE_PRICE = 7

  def self.price(size) = BASE_PRICE + SIZES.fetch(size) / 5
end

p Pizza::SIZES.keys
p Pizza.price(:large)
p Pizza::BASE_PRICE
[:small, :medium, :large]
14
7

Instance methods vs class methods

ruby · try it yourself
class Order
  @next_id = 1

  def self.next_id
    id = @next_id
    @next_id += 1
    id
  end

  attr_reader :id, :items

  def initialize(*items)
    @id = self.class.next_id   # instance code calling a class method
    @items = items
  end

  def summary = "Order ##{id}: #{items.join(', ')}"
end

puts Order.new("soup", "bread").summary
puts Order.new("salad").summary
Order #1: soup, bread
Order #2: salad

Inside an instance method, self.class gives you the object's class, so you can call class methods from there.

Instance method Class method
Defined with def name def self.name or inside class << self
Called on an object: order.summary the class: Order.next_id
Typical use behaviour of one object factories, counters, lookups, configuration

Test yourself

How do you define a class method named build?

  1. def build
  2. def self.build
  3. def class.build
  4. static def build

What is self inside an instance method?

  1. The class
  2. main
  3. The object the method was called on
  4. nil

Which kind of variable is shared between a class and its subclasses?

  1. @var on an instance
  2. @var on the class
  3. @@var
  4. A local variable