如何从枚举器方法中引用该集合?

时间:2017-07-15 05:22:28

标签: ruby

假设我有一个数组:

arr = [53, 55, 51, 60]

现在我调用一些枚举方法。剥离的例子:

arr.each_with_index { |e, i| puts "Element #{i} of #{arr.length} is #{e}" }
#=> Element 0 of 4 is 53
#=> Element 1 of 4 is 55
#=> Element 2 of 4 is 51
#=> Element 3 of 4 is 60

如果我改为:

[1, 10, 100].each_with_index {|e, i| puts "Element #{i} of #{arr.length} is #{e}" }
#=> Element 0 of 4 is 1
#=> Element 1 of 4 is 10
#=> Element 2 of 4 is 100

哪个错误,因为arr仍在引用外部变量。

有没有办法从枚举器方法中返回集合?

1 个答案:

答案 0 :(得分:2)

您可以使用Object#tap,但它确实也会返回原始数组:

[1, 10, 100].tap { |arr|
  arr.each.with_index(1) { |e,i| puts "Element #{i} of #{arr.size} is #{e}" }
}
#=> [1, 10, 100]

打印:

Element 1 of 3 is 1
Element 2 of 3 is 10
Element 3 of 3 is 100

在这里,我们将[1, 10, 100]传递给tap的{​​{1}}所代表的区块,然后我们就会做我们需要的工作。另请注意,我使用的是arr而不是each.with_index(1)。这允许我们将计数器each_with_index偏移到i而不是默认1。与你的例子相关。