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
仍引用外部變量。
有沒有一種方法可以從枚舉器方法內引用回集合?
在lambda? ' - > x {x.each_with_index {| e,i |放置「#{x.length}的元素#{i}是#{e}」}}。([1,10,100])'我也想知道':)' –