Ruby 如何从枚举器方法内部引用集合?
假设我有一个数组:Ruby 如何从枚举器方法内部引用集合?,ruby,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 如果我将其更改为:
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, 10, 100].tap { |arr|
arr.each.with_index(1) { |e,i| puts "Element #{i} of #{arr.size} is #{e}" }
}
#=> [1, 10, 100]
印刷品:
3中的元素1是1
3的元素2是10
3的元素3是100
在这里,我们将
[1,10100]
传递到点击的块,它由arr
表示,然后我们做我们需要的事情。还请注意,我使用了each.with\u index(1)
而不是each\u with\u index
。这允许我们将计数器i
偏移为从1
开始,而不是默认的0
。与您的示例相关。在lambda中->x{x.each_和{u索引{e,i |放置{x.length}中的{i}元素是{e}。([1,10100])
我也在想:)
我在玩.tap
,但没有得到与示例相同的术语。谢谢