img_array = [
[0, 1, 2, 3],
[4, 5, 6, 7],
[8, 9, 0, 1]
]
我们有:
enum = img_array.each
#=> #<Enumerator: [[0, 1, 2, 3], [4, 5, 6, 7], [8, 9, 0, 1]]:each>
Array#each 因此创建了一个枚举器,它是类Enumerator 的一个实例。方法Enumerator#each 将enum 的每个元素传递给块并分配块变量:
enum.each { |row, row_index| puts "row=#{row}, row_index=#{row_index}" }
# row=0, row_index=1
# row=4, row_index=5
# row=8, row_index=9
我们可以通过Enumerator#next的方法看到enum的每个元素是什么:
enum.next #=> StopIteration: iteration reached an end
哎呀!我忘了重置枚举器:
enum.rewind
#=> #<Enumerator: [[0, 1, 2, 3], [4, 5, 6, 7], [8, 9, 0, 1]]:each>
enum.next #=> [0, 1, 2, 3]
enum.next #=> [4, 5, 6, 7]
enum.next #=> [8, 9, 0, 1]
enum.next #=> StopIteration: iteration reached an end
或者,我们可以将枚举数转换为数组(不需要rewind):
enum.to_a #=> [[0, 1, 2, 3], [4, 5, 6, 7], [8, 9, 0, 1]]
将元素([0, 1, 2, 3])传递给块时,块变量的赋值如下:
row, row_index = [0, 1, 2, 3] #=> [0, 1, 2, 3]
row #=> 0
row_index #=> 1
如果变量为|row, row_index, col_index|,则赋值为:
row, row_index, col_index = [0, 1, 2, 3] #=> [0, 1, 2, 3]
row #=> 0
row_index #=> 1
col_index #=> 2
如果他们是|row, row_index, *rest|,那就是:
row, row_index, *rest = [0, 1, 2, 3] #=> [0, 1, 2, 3]
row #=> 0
row_index #=> 1
rest #=> [2, 3]
这称为parallel (or multiple) assignment。您可以在我提供的链接上阅读此类作业的规则。