我想爲基於Ruby數組的對象創建一個容器類。我想操縱這些容器中的多個容器,例如將兩個連接在一起。如果我試試這個:如何引用Ruby中同一類的另一個對象?
class Thing
attr_accessor :name
end
class Things
def initialize
@things = Array.new
end
def addone(a)
@things.push(a)
end
def append(list)
list.each { |i| addone(i) }
end
end
item1 = Thing.new
item2 = Thing.new
item3 = Thing.new
item4 = Thing.new
item1.name = "Marty"
item2.name = "Fred"
item3.name = "Janice"
item4.name = "John"
list1 = Things.new
list1.addone(item1)
list1.addone(item2)
list2 = Things.new
list2.addone(item3)
list2.addone(item4)
list3 = Things.new
list3 = list2.append(list1)
我得到的錯誤:
in
append': undefined method
each' for # (NoMethodError) from ./test.rb:40:in `'
我已經嘗試不同的方法,例如創建每種方法,因爲它似乎想要的,但至今沒有運氣。有什麼建議麼?並提前致謝!
我偷懶的辦法:'高清追加(*列表)'再後來'list.flatten.each {...}' – tadman
除非你要能夠存儲陣列:) – mudasobwa
這會破壞數組事情有點,這是真的。好點子! – tadman