红宝石环路打印额外的东西

问题描述 投票:-2回答:2

我有一个数组的数组中,它看起来是这样的:

[
  [[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

在输出的末尾,我的代码生成额外的东西。

ruby
2个回答
3
投票
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

0
投票

选项筑巢Enumerable#each_with_objectEnumerable#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)


The nested loop operates on each sub-array in this way:
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)"
© www.soinside.com 2019 - 2024. All rights reserved.