我有一个类 A
,我想匿名扩展它并向子类添加一个类方法。例如:
class A
end
Class.new A do
def self.new_class_method
puts 'I am a class method'
end
end.new_class_method
=> I am a class method
上面的例子运行良好,除非你想访问 def self.new_class_method
block 之外的一些变量。例如,
greeting = 'hello'
Class.new A do
def self.new_class_method
puts greeting + ' I am a class method'
end
end.new_class_method
=> NameError: undefined local variable or method `greeting'
我正在使用 Ruby 1.8.7,这令人难过,因为我相信 Ruby 1.9+ 包含一个类似于 define_method
的模拟,它添加了一个类方法。有人有解决 1.8.7 的方法吗?
最佳答案
我已经在 Ruby 1.8.7 中测试了以下内容:-
greeting = 'hello'
class A
end
Class.new A do
meta_klass = class << self; self ;end
meta_klass.send(:define_method, :new_class_method) do
puts greeting + ' I am a class method'
end
end.new_class_method
# >> hello I am a class method
因为 Ruby 1.8.7 不支持 Object#singleton_class
, 我用过 meta_klass = class << self; self ;end
.我认为此方法从 1.9.2 开始可用。
关于ruby - 在定义类方法时规避 Ruby 的作用域门,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23701334/