我有一个数组的数组中,它看起来是这样的:
[
[[1, 3], [3, 0]],
[[0, 0], [0, 3], [3, 2], [3, 3]],
[[0, 1], [0, 2], [1, 0], [2, 0], [2, 3], [3, 1]],
[[1, 2], [2, 2]],
[[1, 1], [2, 1]]
]
我想打印每一个元素。我希望这样的输出:
0,(1,3),(3,0)
1,(0,0),(0,3),(3,2),(3,3)
2,(0,1),(0,2),(1,0),(2,0),(2,3),(3,1)
3,(1,2),(2,2)
4,(1,1),(2,1)
这是我的代码:
for indx in 0..4
print "#{indx}"
for cell in cell_arr[indx]
print ",(#{cell[0]},#{cell[1]})"
end
if indx <= 4
puts
end
end
我得到的输出:
0,(1,3),(3,0)
1,(0,0),(0,3),(3,2),(3,3)
2,(0,1),(0,2),(1,0),(2,0),(2,3),(3,1)
3,(1,2),(2,2)
4,(1,1),(2,1)
0..4
在输出的末尾,我的代码生成额外的东西。
0..4
是的,如果调用返回
for i in 0..100
end
回报将是
0..100
逃脱这样的:
for indx in 0..4
print "#{indx}"
for cell in cell_arr[indx]
print ",(#{cell[0]},#{cell[1]})"
end
if indx <= 4
puts
end
end; nil
选项筑巢Enumerable#each_with_object
内Enumerable#each_with_index
:
array.map.with_index { |ary, i| (ary.each_with_object ([]) { |e, tmp| tmp << "(#{e.first}, #{e.last})" }).unshift(i).join(',') }
这使:
# 0,(1, 3),(3, 0)
# 1,(0, 0),(0, 3),(3, 2),(3, 3)
# 2,(0, 1),(0, 2),(1, 0),(2, 0),(2, 3),(3, 1)
# 3,(1, 2),(2, 2)
# 4,(1, 1),(2, 1)
sub_arry = [[0, 1], [0, 2], [1, 0], [2, 0], [2, 3], [3, 1]]
res = sub_arry.each_with_object ([]) { |e, tmp| tmp << "(#{e.first}, #{e.last})" }
res #=> ["(0, 1)", "(0, 2)", "(1, 0)", "(2, 0)", "(2, 3)", "(3, 1)"]
这个想法是把该数组内的元素的索引,然后使用Array#join
构建行要打印:
res.unshift(2).join(',')
#=> "2,(0, 1),(0, 2),(1, 0),(2, 0),(2, 3),(3, 1)"