在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行检索默认值。但有办法不提卡车吗?似乎应该有。
要访问实例方法中的类方法,请执行以下操作:
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
下面是一种如何在这种情况下实现作为self.class的_class方法的方法。注意:不要在产品代码中使用它,这是出于兴趣考虑:)
你能在Ruby调用者的上下文中评估代码吗?还有http://rubychallenger.blogspot.com.au/2011/07/caller-binding.html
# Rabid monkey-patch for Object
require 'continuation' if RUBY_VERSION >= '1.9.0'
class Object
def __; eval 'self.class', caller_binding; end
alias :_class :__
def caller_binding
cc = nil; count = 0
set_trace_func lambda { |event, file, lineno, id, binding, klass|
if count == 2
set_trace_func nil
cc.call binding
elsif event == "return"
count += 1
end
}
return callcc { |cont| cc = cont }
end
end
# Now we have awesome
def Tiger
def roar
# self.class.roar
__.roar
# or, even
_class.roar
end
def self.roar
# TODO: tigerness
end
end
也许正确的答案是为Ruby提交一个补丁:)