带有附加参数的“每个”循环

`each` loop with additional parameter

我预计 row[0, 0, 0, 0]row_indexnil,如下所示:

img_array = [
  [0, 0, 0, 0],
  [0, 0, 0, 0],
  [0, 0, 0, 0],
  [0, 1, 0, 0],
  [0, 0, 0, 0],
  [0, 0, 0, 0]
]

img_array.each do |row, row_index|
  ...
end

实际上,row0row_index0。谁能解释一下?

Ruby 中数组上的方法 .each() 将仅使用一个参数调用您的块。 所以如果你这样写你的代码:

img_array.each do |row, row_index|
  # do something here
end

它将等同于:

img_array.each do |element|
  row, row_index = element
  # and now
  # row = element[0]
  # row_index = element[1]
end

我举了一个更容易理解的例子

img_array = [
  ['a', 'b', 'd', 'e'],
  ['f', 'g', 'h', 'j']
]

img_array.each do |row, row_index|
    p row
    p row_index
end

结果将是:

"a"
"b"
"f"
"g"

运行 在这里在线:https://ideone.com/ifDaVZ

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 therefore creates an enumerator that is an instance of the class Enumerator. The method Enumerator#eachenum 的每个元素传递给块并分配块变量:

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。您可以在我提供的 link 中阅读此类作业的规则。