Class Methods
Part of the Object Oriented Programming section of Coddy's Ruby journey. Lesson 12 of 57.
A class method belongs to the class, not to one instance. In the class body self is the class, so def self.name defines a method on the class. You call it on the class itself:
class Temperature
def self.to_fahrenheit(celsius)
celsius * 9 / 5.0 + 32
end
end
puts Temperature.to_fahrenheit(100)
puts Temperature.to_fahrenheit(-40)Output:
212.0
-40.0Class methods and instance methods live in different places. An instance cannot call a class method directly; it reaches it through self.class or the class name:
class Circle
def self.area_for(r)
(3.14159 * r * r).round(2)
end
def initialize(r)
@r = r
end
def area
self.class.area_for(@r)
end
end
puts Circle.area_for(1)
puts Circle.new(2).area
begin
Circle.new(2).area_for(2)
rescue NoMethodError => e
puts e.message
endOutput:
3.14
12.57
undefined method `area_for' for an instance of Circleclass << self opens a section of the class body in which every def is a class method. It saves writing self. when a class has several of them:
class Units
class << self
def km_to_miles(km)
(km * 0.621371).round(1)
end
def miles_to_km(miles)
(miles / 0.621371).round(1)
end
end
end
puts Units.km_to_miles(10)
puts Units.miles_to_km(26.2)Output:
6.2
42.2Use a class method for work that belongs to the kind of thing rather than to one object: converting units, parsing text into an object or keeping a count of all instances. Work that needs one object's data stays an instance method:
class Invoice
def self.tax_rate # the same for every invoice
0.2
end
def tax # needs this invoice's amount
@amount * Invoice.tax_rate
end
endChallenge
EasyComplete the class methods of Temperature. to_fahrenheit(c) and to_celsius(f) convert a value. feel(celsius) returns freezing below 0, cold below 15, mild below 25 and hot otherwise. convert(text) takes text such as 20 C or 68 F and returns 20.0 C = 68.0 F (mild) or 68.0 F = 20.0 C (mild), with one decimal and the feel of the Celsius value; it uses the other class methods.
The supplied code calls Temperature.convert(line) for every input line and prints the result. No instance of Temperature is created.
Your code goes in temperature.rb. main.rb holds the supplied input/output code and cannot be edited.
Try it yourself
require_relative 'temperature'
# Supplied input/output code: keep it as it is
input = []
while (line = gets)
input << line.chomp
end
input.each { |line| puts Temperature.convert(line) }
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Object Oriented Programming
1Classes and Objects
Working With FilesDefining ClassesInstance VariablesMethods and selfto_s and inspectRecap - Library Card7Polymorphism and Duck Typing
PolymorphismDuck TypingAbstract Methodscase and ClassesRecap - Payment Methods2Accessors and Self
Readers and WritersCustom Settersself in MethodsIdentity and EqualityRecap - Contact List8Special Methods
Equality and hashOperator MethodsIndexing and AppendingCustom CollectionsRecap - Fractions11Project: Library Management
Books and MembersBorrowing Books3Class Methods and Variables
Class MethodsClass Instance VariablesConstantsFactory MethodsRecap - Coupon CodesPractice on your own: Online Ruby compiler