Ruby: Calling class method from instance

后端 未结 9 2053
谎友^
谎友^ 2021-01-29 17:26

In Ruby, how do you call a class method from one of that class\'s instances? Say I have

class Truck
  def self.default_make
    # Class method.
    \"mac\"
  end         


        
9条回答
  •  一个人的身影
    2021-01-29 18:23

    To access a class method inside a instance method, do the following:

    self.class.default_make
    

    Here is an alternative solution for your problem:

    class Truck
    
      attr_accessor :make, :year
    
      def self.default_make
        "Toyota"
      end
    
      def make
        @make || self.class.default_make
      end
    
      def initialize(make=nil, year=nil)
        self.year, self.make = year, make
      end
    end
    

    Now let's use our class:

    t = Truck.new("Honda", 2000)
    t.make
    # => "Honda"
    t.year
    # => "2000"
    
    t = Truck.new
    t.make
    # => "Toyota"
    t.year
    # => nil
    

提交回复
热议问题