Class Methods and Class-Level Data
Prerequisites: Instance methods, self, and to_s
Instance methods belong to objects. Class methods belong to the
class itself — you call them on the class name, like Dog.new or
Time.now.
Syntax
Inside a class body, self is the class, so def self.name defines a
class method:
class Converter
def self.km_to_miles(km)
(km * 0.621371).round(2)
end
end
p Converter.km_to_miles(10)
6.21
Named constructors
A common use is an alternative way to create objects:
class User
attr_reader :name, :email
def initialize(name, email)
@name = name
@email = email
end
def self.from_hash(data)
new(data.fetch(:name), data.fetch(:email))
end
end
user = User.from_hash({ name: "Ada", email: "ada@example.com" })
puts user.email
ada@example.com
Inside a class method, new means self.new — creating an instance of
this class.
Constants in classes
Values shared by every instance usually belong in a constant:
class Order
TAX_RATE = 0.2
def initialize(subtotal)
@subtotal = subtotal
end
def total = @subtotal * (1 + TAX_RATE)
end
p Order.new(100).total
p Order::TAX_RATE
120.0
0.2
Order::TAX_RATE reads a constant from outside the class.
Ruby also has class variables (@@count), but they're shared with
every subclass in surprising ways, and most style guides advise
avoiding them. Use a constant, or an instance variable on the class
itself, instead.
Common mistakes
- Calling a class method on an instance (
user.from_hash(...)) —NoMethodError. Class methods are called on the class.