Ruby: Calling class method from instance

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

    One more:

    class Truck
      def self.default_make
        "mac"
      end
    
      attr_reader :make
    
      private define_method :default_make, &method(:default_make)
    
      def initialize(make = default_make)
        @make = make
      end
    end
    
    puts Truck.new.make # => mac
    

提交回复
热议问题