2013-03-06 25 views
2

在Ruby中,Struct類的new方法創建一個Struct的子類,其行爲基於傳遞給它的參數而有所不同。我如何在Ruby中對自己的類做類似的事情? (我剛纔複製Struct的源代碼,但它是用C語言編寫)在Ruby中,我如何實現一個類,其新方法創建自己的子類?

irb(main):001:0> Foo = Struct.new(:foo, :bar) 
=> Foo 
irb(main):002:0> x = Foo.new 
=> #<struct Foo foo=nil, bar=nil> 
irb(main):003:0> Foo.superclass 
=> Struct 

回答

3
class A 
    def self.new; Class.new(self) end 
end 

A.new # => #<Class:0x007f009b8e4200> 

編輯這可能會更好地適應OP的意圖。

class A 
    singleton_class.class_eval{alias :old_new :new} 
    def self.new 
    Class.new(self){singleton_class.class_eval{alias :new :old_new}} 
    end 
end 
+1

啊,好吧,這是有道理的。謝謝你的幫助。 :+1: – Ajedi32 2013-03-06 20:37:36

相關問題