gpt4 book ai didi

Ruby:从实例调用类方法

转载 作者:数据小太阳 更新时间:2023-10-29 06:16:17 25 4
gpt4 key购买 nike

在 Ruby 中,如何从类的实例之一调用类方法?说我有

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

def initialize
# Instance method.
Truck.default_make # gets the default via the class's method.
# But: I wish to avoid mentioning Truck. Seems I'm repeating myself.
end
end

Truck.default_make 行检索默认值。但是有没有一种方法可以在不提及 Truck 的情况下表达这一点?好像应该有。

最佳答案

无需引用类的字面名称,在实例方法中您只需调用 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

输出:

Class method: FooInstance method: Foo

关于Ruby:从实例调用类方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2527830/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com