2017-07-15 28 views
1

假设我有一个数组:如何从枚举器方法内引用集合?

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

在lambda? ' - > x {x.each_with_index {| e,i |放置“#{x.length}的元素#{i}是#{e}”}}。([1,10,100])'我也想知道':)' –

回答

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的块,其中它是由arr表示,则我们做我们需要的。另请注意,我用each.with_index(1)而不是each_with_index。这允许我们抵消i的计数器以开始1而不是默认的0。与你的例子有关。

+1

我正在玩'.tap',但还没有完全达到与例子相同的条件。谢谢。 – dawg