我的问题是,我有一堆扩展Struct.new的类。现在我需要为所有这些添加一个公共类方法。 如果Struct是一个“普通”超类,我可以在其上定义一个类方法,然后每个子类也会有该方法。
鉴于它不是,我该如何复制这种行为? 例如,
class Foo < Struct.new(:foo); end
Foo.respond_to?(:perform) #=> true
class Bar < Struct.new(:bar); end
Bar.respond_to?(:perform) #=> true
答案 0 :(得分:2)
为什么不能在Struct上定义方法?
def Struct.perform
end
class Foo < Struct.new(:foo); end
Foo.respond_to?(:perform) #=> true
class Bar < Struct.new(:bar); end
Bar.respond_to?(:perform) #=> true