2017-02-04 98 views
-1

所以如果我有兩個數組在不同的類中,最簡單的方法是從完整數組中刪除所有對象並將它們添加到另一個類的空數組中。例如,這將是一個前將數組對象從一個數組發送到另一個類之間的另一個數組ruby

class Red 
    def initialize 
    @red_array = [] 
    end 
end 


class Blue 
    @blue_array = [red_object, red_object2, red_object3] 
end 

,這將是後

class Red 
    def initialize 
    @red_array = [red_object, red_object2, red_object3] 
    end 
end 


class Blue 
    @blue_array = [] 
end 
+0

這只是出於好奇或做你有這樣做的理由? FYI:第一個實例變量屬於Red實例,而第二個實例變量屬於Class,Blue實例。 –

+0

我這樣做是因爲我實際上試圖模擬餅乾麪包店。在我的實際代碼中,我有一個充滿cookie對象的托盤,它是烤箱類的一部分,我想將該數組放在店面類中,因此我將它們從托盤中移除,然後將它們放在店面陣列中...希望有所幫助! –

+0

問我是否好奇,沒有回答我的問題有什麼意義。這是我的問題,所以我應該期待一個答案。不是你...... –

回答

1

根據您的描述您的解決方案是有點這個

class Red 
    attr_accessor :red_array 

    def initialize 
    @red_array = [] 
    end 
end 

class Blue 
    attr_accessor :blue_array 

    def initialize 
    @blue_array = [] 
    end 
end 

reds = Array.new(3,Red.new) 

red = Red.new 
red.red_array = reds 

blue = Blue.new 
blue.blue_array, red.red_array = red.red_array, blue.blue_array 
+1

'blue.blue_array,red.red_array = red.red_array,blue.blue_array' –

+0

@EricDuminil不錯!讓我改變它。謝謝! –

相關問題