Project

General

Profile

Actions

Feature #15618

closed

Implement Enumerator::Yielder#to_proc

Added by knu (Akinori MUSHA) over 5 years ago. Updated over 5 years ago.

Status:
Closed
Assignee:
-
Target version:
-
[ruby-core:91613]

Description

When writing an Enumerator block, you often want to delegate iteration to another method like this:

enum = Enumerator.new { |y|
  Dir.glob("*.rb") { |file|
    File.open(file) { |f| f.each_line { |line| y << line } }
  }
}

I think this is such a common pattern, but the { |var| y << var } part looks redundant compared to a normal iterator method being able to delegate to another method as simply as follows:

  def each(&block)
    @children.each(&block)
  end

So, I propose adding #to_proc to Yielder so you can directly pass a yielder object to another method as a block argument.

enum = Enumerator.new { |y|
  Dir.glob("*.rb") { |file|
    File.open(file) { |f| f.each_line(&y) }
  }
}

Yielder is all about yielding, so I think it's pretty obvious what it means.


Files

Actions

Also available in: Atom PDF

Like0
Like0Like0Like0