Project

General

Profile

Actions

Feature #21701

open

Enumerator.produce accepts an optional `size` keyword argument

Feature #21701: Enumerator.produce accepts an optional `size` keyword argument

Added by knu (Akinori MUSHA) about 4 hours ago.

Status:
Open
Target version:
[ruby-core:123875]

Description

Enumerator::Producer#size currently always returns Float::INFINITY, and it is not specifiable.

However, a produce sequence is known to be at least finite in many cases, and you can even tell or compute the exact size in some cases.

# Infinite enumerator
enum = Enumerator.produce(1, size: Float::INFINITY, &:succ)
enum.size  # => Float::INFINITY

# Finite enumerator with known/computable size
abs_dir = File.expand_path("./baz") # => "/foo/bar/baz"
traverser = Enumerator.produce(abs_dir, size: -> { abs_dir.count("/") + 1 }) {
  raise StopIteration if it == "/"
  File.dirname(it)
}
traverser.size  # => 4

As a background, Enumerator#to_set was changed to refuse to work against an infinite enumerator in https://bugs.ruby-lang.org/issues/21513.
That made #to_set always fail against produce sequences. This enhancement will fix the problem (kind of) safely, and we will also be able to add the same size check to #to_a, which is currently missing and inconsistent with #to_set.

Here's the implementation: https://github.com/ruby/ruby/pull/15277


Related issues 1 (0 open1 closed)

Related to Ruby - Bug #21513: Converting endless range to set hangsClosedknu (Akinori MUSHA)Actions

Updated by knu (Akinori MUSHA) about 3 hours ago Actions #1

  • Related to Bug #21513: Converting endless range to set hangs added
Actions

Also available in: PDF Atom