Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/ruby/21.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby 如何从枚举器方法内部引用集合?_Ruby - Fatal编程技术网

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
,但没有得到与示例相同的术语。谢谢