Ruby: Calling class method from instance

后端 未结 9 2170
谎友^
谎友^ 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:19

    Using self.class.blah is NOT the same as using ClassName.blah when it comes to inheritance.

    class Truck
      def self.default_make
        "mac"
      end
    
      def make1
        self.class.default_make
      end
    
      def make2
        Truck.default_make
      end
    end
    
    
    class BigTruck < Truck
      def self.default_make
        "bigmac"
      end
    end
    
    ruby-1.9.3-p0 :021 > b=BigTruck.new
     => # 
    ruby-1.9.3-p0 :022 > b.make1
     => "bigmac" 
    ruby-1.9.3-p0 :023 > b.make2
     => "mac" 
    

提交回复
热议问题