Module 03 Β· Classes & Modules β Lesson 4 of 6 Β· ~9 min
Class Methods & Constants
def self.method_name β a method on the CLASS, not an instance
Every method you've written so far runs on an instance: priya.price_label. Sometimes the logic doesn't belong to any one walker β it's about walkers in general: finding the cheapest one, building one from raw data, counting how many exist. Prefix def with self. and the method attaches to the class itself instead:
class Walker
def self.cheapest(walkers)
walkers.min_by(&:price_per_30_min_cents)
end
end
Walker.cheapest([priya, sam]) # called on the CLASS, not an instancewalkers.min_by(&:price_per_30_min_cents) is the &:symbol block shorthand from module 02 β it's equivalent to walkers.min_by { |w| w.price_per_30_min_cents }. Compare this to Swift's static func or Python's @classmethod β different keywords, identical idea: a method that belongs to the type, not to one instance of it.