Search
⌘K
    to navigateEnterto select Escto close

    Use self to declare class methods

    We prefer using self.method_name instead of the class << self way of defining class methods.

    1class Apple
    2  def is_green?
    3  end
    4
    5  class << self
    6    def all_apples
    7    end
    8  end
    9
    10  def another_method
    11  end
    12end

    When reading this class with the number of methods defined, it's hard to tell the difference between a class method and an instance method when the methods are using class << self.

    1class Apple
    2  def is_green?
    3  end
    4
    5  def self.all_apples
    6  end
    7
    8  def another_method
    9  end
    10end

    Here, the class method is clearly defined and there is no ambiguity when reading this class. Moreover, it is now easier to refactor and maintain.

    Previous
    Next