2012-09-01 82 views
2
def initialize() 
    @attribute = AnotherClass.new(self) 
end 

我將從python進行ruby。在Python中,我知道我可以將自己作爲一個對象傳遞給一個函數。 現在,我想將自己傳遞給另一個類的初始化方法。我怎樣才能做到這一點?Ruby通過自我初始化實例

+1

你嘗試了嗎? –

回答

4

就在你所期望的方式:

class A 
    def initialize(foo) 
    @foo = foo 
    end 
end 

class B 
    attr_reader :bar 

    def initialize 
    @bar = A.new(self) 
    end 
end 

B.new.bar.class #=> A