[英]What is the proper way to use methods that return an enumerator in Ruby array?
Many methods in Ruby array return an enumerator when invoked without parameters or blocks ( index
, keep_if
, each
, drop_while
and many more). 在没有参数或块(
index
, keep_if
, each
, drop_while
等等)的情况下调用时, Ruby数组中的许多方法都返回一个枚举器。
From the docs to Enumerator
: 从文档到
Enumerator
:
Most methods have two forms: a block form where the contents are evaluated for each item in the enumeration, and a non-block form which returns a new Enumerator wrapping the iteration.
大多数方法都有两种形式:一种是块形式,其中内容是为枚举中的每个项目计算的,另一种是非块形式,它返回一个包含迭代的新枚举器。
This allows you to chain Enumerators together.
这允许您将枚举器链接在一起。 For example, you can map a list's elements to strings containing the index and the element as a string via:
例如,您可以将列表的元素映射到包含索引的字符串,并将元素映射为字符串,方法是:
puts %w[foo bar baz].map.with_index {|w,i| "#{i}:#{w}" } # => ["0:foo", "1:bar", "2:baz"]
An Enumerator can also be used as an external iterator.
枚举器也可以用作外部迭代器。 For example, Enumerator#next returns the next value of the iterator or raises StopIteration if the Enumerator is at the end.
例如,Enumerator#next返回迭代器的下一个值,或者如果Enumerator在结尾处则引发StopIteration。
e = [1,2,3].each # returns an enumerator object. puts e.next # => 1 puts e.next # => 2 puts e.next # => 3 puts e.next # raises StopIteration
I'm sorry for copy-paste, but I couldn't explain better. 我很抱歉复制粘贴,但我无法解释得更好。
The main original reason for the Enumerator class to exist is method chaining: Enumerator类存在的主要原因是方法链:
array.each.with_object [[], []] { |element, memo| ... }
So basically, you don't need to worry about that. 所以基本上,你不必担心这一点。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.