Project

General

Profile

Actions

Feature #17663

open

Enumerator#with, an alternative to Enumerator#with_object

Added by RichOrElse (Ritchie Buitre) about 3 years ago. Updated about 3 years ago.

Status:
Open
Assignee:
-
Target version:
-
[ruby-core:102644]

Description

Enumerator#with yields each element along with the arguments

class Enumerator
  def with(*options)
    return to_enum(:with, *options) unless defined? yield

    each do |entry|
      yield entry, *options
    end
  end
end

Suppose we have a proc that accepts more than 1 argument.

format = proc do |value, *option|
  value.to_s(*option)
end

Normally to apply the argument we enclosed it in a block, like so:

(10..15).map { |n| format.(n, 16) } # => ["a", "b", "c", "d", "e", "f"]

I found Enumerator#with_object method awkward to use.

(10..15).each.with_object(16).map(&format) # => ["a", "b", "c", "d", "e", "f"]

Tried simplifying this code further, but Enumerator#with_object ignores the given block and just returns the argument.

(10..15).map.with_object(16, &format) # => 16

Compare to how concise this line using Enumerator#with

(10..15).map.with(16, &format)  # => ["a", "b", "c", "d", "e", "f"]

Actions

Also available in: Atom PDF

Like0
Like0Like0Like0Like0Like0