2017-07-15 30 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