【问题标题】:`each` loop with additional parameter带有附加参数的“每个”循环
【发布时间】:2016-02-21 00:50:22
【问题描述】:

我预计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

其实row就是0row_index就是0。谁能解释一下?

【问题讨论】:

  • 无法复制。它甚至无效。
  • @sawa 它在 ruby​​-2.2.2 中对我来说运行良好,并产生了所描述的结果。

标签: ruby loops iteration each


【解决方案1】:

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

【讨论】:

  • 我检查了它,它就像你说的那样运行。谢谢你的解释。它真的帮助了我!
  • @EricOrel 不客气。如果此答案解决了您的问题,请将此答案标记为已接受,以便其他人可以更轻松地找到它。
【解决方案2】:
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#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。您可以在我提供的链接上阅读此类作业的规则。

【讨论】:

  • 优秀的答案。形成这个我明白OP的问题实际上是什么:D
  • 卡里这完全有道理!感谢您清晰、深入的意见。我现在对枚举器的工作原理有了更好的了解。
猜你喜欢
  • 2017-02-16
  • 2013-03-20
  • 1970-01-01
  • 1970-01-01
  • 2019-07-12
  • 1970-01-01
  • 1970-01-01
  • 2015-03-18
  • 2022-10-05
相关资源
最近更新 更多