
Issue #20664 has been updated by matheusrich (Matheus Richard).
The one problem we don’t currently have neither Enumerable#take_until, nor Object#not_nil?, to write something like
After [proposing `Object#chain_of`](https://bugs.ruby-lang.org/issues/20625), I realized how missing one of these really makes things harder than they need to. With 3.4's `it`, the expression gets a bit more readable: ```ruby Enumerator.produce(File, &:superclass).take_while { !it.nil? } ``` IMO this pattern is common enough to deserve an optimization. `#not_nil?` would probably be harder to add (people will start talking about `present?` and how it is longer than `!<>.nil?`, so maybe proposing `#take_until` will be easier to get approval. ---------------------------------------- Feature #20664: Add `before` and `until` options to Enumerator.produce https://bugs.ruby-lang.org/issues/20664#change-109465 * Author: knu (Akinori MUSHA) * Status: Open ---------------------------------------- Enumerator.produce provides a nice way to generate an infinite sequence but is a bit awkward to define how to end a sequence. It lacks a simple and easy way to produce typical finite sequences in an intuitive syntax. This proposal attempts to solve the problem by adding these two options to the method: - `before`: when provided, it is used as a predicate to determine if an iteration should end before a generated value gets yielded. - `until`: when provided, it is used as a predicate to determine if an iteration should end until after a generated value gets yielded. Any value that responds to `to_proc` and returns a `Proc` object is accepted in these options. A typical use case for the `before` option is traversing a tree structure to iterate over the ancestors or following/preceding siblings of a node. The `until` option can be used when there is a clear definition of the "last" value to yield. ```ruby enum = Enumerator.produce(File, before: :nil?, &:superclass) enum.to_a #=> [File, IO, Object, BasicObject] enum = Enumerator.produce(3, until: :zero?, &:pred) enum_to_a #=> [3, 2, 1, 0] ``` ---Files-------------------------------- 0001-Add-before-and-until-options-to-Enumerator.produce.patch (10.7 KB) -- https://bugs.ruby-lang.org/