在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行检索默认值。但有办法不提卡车吗?似乎应该有。
你做得对。类方法(类似于c++或Java中的“静态”方法)不是实例的一部分,因此必须直接引用它们。
关于这一点,在你的例子中,你最好将'default_make'设置为常规方法:
#!/usr/bin/ruby
class Truck
def default_make
# Class method.
"mac"
end
def initialize
# Instance method.
puts default_make # gets the default via the class's method.
end
end
myTruck = Truck.new()
类方法对于使用该类的实用程序类型函数更有用。例如:
#!/usr/bin/ruby
class Truck
attr_accessor :make
def default_make
# Class method.
"mac"
end
def self.buildTrucks(make, count)
truckArray = []
(1..count).each do
truckArray << Truck.new(make)
end
return truckArray
end
def initialize(make = nil)
if( make == nil )
@make = default_make()
else
@make = make
end
end
end
myTrucks = Truck.buildTrucks("Yotota", 4)
myTrucks.each do |truck|
puts truck.make
end
下面是一种如何在这种情况下实现作为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提交一个补丁:)