Ruby: Calling class method from instance

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

    Rather than referring to the literal name of the class, inside an instance method you can just call self.class.whatever.

    class Foo
        def self.some_class_method
            puts self
        end
    
        def some_instance_method
            self.class.some_class_method
        end
    end
    
    print "Class method: "
    Foo.some_class_method
    
    print "Instance method: "
    Foo.new.some_instance_method
    

    Outputs:

    Class method: Foo
    Instance method: Foo
    

提交回复
热议问题