`Ticket.new` and `Ticket.most_expensive(...)` send messages to the same receiver: the class object `Ticket`. The first creates a ticket; the second asks the class to compare several tickets. Sending `most_expensive` to an individual ticket fails. A class object has its own identity, methods, and state, separate from every instance it creates. section 3.6.2 section 3.6.3 section 3.6.5
Every class is an instance of `Class`. A `class Ticket ... end` definition creates a class object, but `my_class = Class.new` creates one too. The latter can be held in a local variable rather than the constant normally used for a class; `my_class.new` then creates an instance of it. A block passed to `Class.new` can define instance methods for those future instances. section 3.6.1
c = Class.new do
def say_hello
puts "Hello!"
end
end
An anonymous class receives an instance-method definition in the block passed to `Class.new`. section 3.6.1
Class objects receive methods much as other objects do. `Ticket.new` works because `new` is an instance method of `Class`; calls such as `attr_reader` inside a class body work because classes can use methods from `Module`, the superclass of `Class`. In that body, `self` is the class object, so a bare `attr_reader` call goes to `Ticket` and creates readers for ticket instances. section 3.6.2 section 3.4.1
def Ticket.most_expensive(*tickets)
tickets.max_by(&:price)
end
Defining `Ticket.most_expensive` attaches a singleton method directly to the class object. Such a method is commonly called a class method; it is not an instance method of `Ticket`. section 3.6.3 section 3.6.5
State follows the receiver too. An `@v` assigned while `self` is a class object belongs to that class object, not to an instance whose method also refers to `@v`. Class variables serve a different purpose: they can be visible to both class-method and instance-method definitions. A car tracker uses that shared visibility for registered makes and counts, while each car keeps its own make in an instance variable. section 5.1.5 section 5.2.5
There is one useful wrinkle in method lookup: a subclass can call a singleton method defined on its parent class object. Ruby finds it through the inheritance relationship between the class objects’ singleton classes. Thus, a method attached to a class is separate from its instances’ methods without necessarily being limited to calls on that one class object. section 13.1.4
Choosing a class-level operation
Put a conversion on `Temperature` when it makes sense to call `Temperature.c2f(100)` without creating a temperature instance. Put a method such as `price` on a ticket instance when the answer depends on that particular ticket. Both choices are ordinary method calls; the receiver differs. section 3.6.4 section 3.6.5
