2012-07-19 43 views
0

我的問題是,我有一堆擴展Struct.new的類。現在我需要爲它們添加一個通用的類方法。 如果Struct是一個'普通'的超類,我就可以在其上定義一個類方法,然後每個子類也有該方法。如何讓Struct.new生成的每個類具有類方法?

鑑於,它不是,我該如何複製這種行爲? 例如,

class Foo < Struct.new(:foo); end 
Foo.respond_to?(:perform) #=> true 
class Bar < Struct.new(:bar); end 
Bar.respond_to?(:perform) #=> true 
+0

在模塊中定義它幷包含到你的子類中。 – 2012-07-19 18:32:47

+0

這是我最初的方法,但它很容易出錯。 – 2012-07-19 19:10:17

回答

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 
+0

太簡單了。謝謝!但是這與''Struct類; def執行;結束;結束'''? – 2012-07-19 19:25:27

+1

這將添加一個實例方法 – 2012-07-19 20:01:33

+0

糟糕,我的意思是'''類結構; def self.perform;結束;結束''' – 2012-07-20 01:17:47

相關問題