Skip to content
instance method

Enumerator#size

() -> (::Integer | ::Float)?
e.size → int, Float::INFINITY or nil

Returns the size of the enumerator, or nil if it can’t be calculated lazily.

Example
(1..100).to_a.permutation(4).size # => 94109400
loop.size # => Float::INFINITY
(1..100).drop_while.size # => nil

Note that enumerator size might be inaccurate, and should be rather treated as a hint. For example, there is no check that the size provided to ::new is accurate:

Example
e = Enumerator.new(5) { |y| 2.times { y << it} }
e.size # => 5
e.to_a.size # => 2

Another example is an enumerator created by ::produce without a size argument. Such enumerators return Infinity for size, but this is inaccurate if the passed block raises StopIteration:

Example
e = Enumerator.produce(1) { it + 1 }
e.size # => Infinity

e = Enumerator.produce(1) { it > 3 ? raise(StopIteration) : it + 1 }
e.size # => Infinity
e.to_a.size # => 4
See also #rewind #with_index #peek_values #with_object also in 4.1 · 3.4 · 3.3 · 3.2 · 3.1 · 3.0