我有四个数组(名为array1,2,3,4),每个数组有8个对象,并希望将它们分为8个空数组,每个数组由4个对象组成,即将数组1中的每个对象放入一个空数组。
?? << array1.shift until array.empty?
我不知道如何迭代8个空数组,以便每个数组从array1接收一个对象
e.g
array1 = clubs1-8
array2 = spades1-8
array3 = hearts1-8
array4 = diamonds1-8
8个空数组或玩家,每个玩家从array1发一张牌,然后从array2等发一张牌。
感谢您的回答,但我希望迭代添加对象,以便根据已添加到每个数组的对象添加条件
e.g
在8个空数组中分配array1
在8个数组中分配array2,但在此之前检查没有数组包含相同的卡号(它不能同时拥有2颗心和2颗钻石)
答案 0 :(得分:2)
你的意思是这样吗?
require "matrix"
a1 = (0..7).to_a
a2 = (8..15).to_a
a3 = (16..23).to_a
a4 = (24..31).to_a
Matrix[a1, a2, a3, a4].transpose.to_a #=> [[0, 8, 16, 24], [1, 9, 17, 25], [2, 10, 18, 26], [3, 11, 19, 27], [4, 12, 20, 28], [5, 13, 21, 29], [6, 14, 22, 30], [7, 15, 23, 31]]
<强>加了:强>
事实上,它更加微不足道:
a1.zip(a2, a3, a4) #=> [[0, 8, 16, 24], [1, 9, 17, 25], [2, 10, 18, 26], [3, 11, 19, 27], [4, 12, 20, 28], [5, 13, 21, 29], [6, 14, 22, 30], [7, 15, 23, 31]]
答案 1 :(得分:1)
迭代不是唯一的方法。试试这个(假设a1..a8是你的8个空数组):
a1, a2, a3, a4, a5, a6, a7, a8 = array1.zip(array2, array3, array4)
答案 2 :(得分:0)
irb(main):001:0> ar1 = [1,2,3,4,5,6,7,8]
=> [1, 2, 3, 4, 5, 6, 7, 8]
irb(main):002:0> ar2 = [2,3,4,1,2,3,2,1]
=> [2, 3, 4, 1, 2, 3, 2, 1]
irb(main):003:0> ar3 = [4,3,5,6,3,3,4,5]
=> [4, 3, 5, 6, 3, 3, 4, 5]
irb(main):004:0> ar4 = [5,2,5,6,7,2,2,5]
=> [5, 2, 5, 6, 7, 2, 2, 5]
irb(main):005:0> ar1.zip(ar2,ar3,ar4)
=> [[1, 2, 4, 5], [2, 3, 3, 2], [3, 4, 5, 5], [4, 1, 6, 6], [5, 2, 3, 7], [6, 3, 3, 2], [7, 2, 4, 2], [8, 1, 5, 5]]