在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行检索默认值。但有办法不提卡车吗?似乎应该有。
如果你可以访问委托方法,你可以这样做:
[20] pry(main)> class Foo
[20] pry(main)* def self.bar
[20] pry(main)* "foo bar"
[20] pry(main)* end
[20] pry(main)* delegate :bar, to: 'self.class'
[20] pry(main)* end
=> [:bar]
[21] pry(main)> Foo.new.bar
=> "foo bar"
[22] pry(main)> Foo.bar
=> "foo bar"
或者,如果你有一个或两个以上的方法,你想委托给类和实例:
[1] pry(main)> class Foo
[1] pry(main)* module AvailableToClassAndInstance
[1] pry(main)* def bar
[1] pry(main)* "foo bar"
[1] pry(main)* end
[1] pry(main)* end
[1] pry(main)* include AvailableToClassAndInstance
[1] pry(main)* extend AvailableToClassAndInstance
[1] pry(main)* end
=> Foo
[2] pry(main)> Foo.new.bar
=> "foo bar"
[3] pry(main)> Foo.bar
=> "foo bar"
提醒一句:
不要只是随机地将所有不改变状态的东西委托给类和实例,因为这会开始遇到奇怪的名称冲突问题。这样做是有节制的,只有在你检查没有其他压扁。
要访问实例方法中的类方法,请执行以下操作:
self.class.default_make
这里有一个解决你的问题的替代方案:
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
现在让我们使用我们的类:
t = Truck.new("Honda", 2000)
t.make
# => "Honda"
t.year
# => "2000"
t = Truck.new
t.make
# => "Toyota"
t.year
# => nil