Project

General

Profile

Feature #15618

Implement Enumerator::Yielder#to_proc

Added by knu (Akinori MUSHA) about 2 months ago. Updated about 1 month ago.

Status:
Closed
Priority:
Normal
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

History

Updated by shevegen (Robert A. Heiler) about 2 months ago

I have no particularly strong pro or con opinion on the functionality itself.

I have only one comment about syntax, though. While { |line| y << line } }
may or may not be redundant (let's leave that open for the moment), and is
definitely longer than the other variant suggested, I think it is actually a
simpler-to-understand syntax compared to the .each_line(&y) variant.

Updated by matz (Yukihiro Matsumoto) about 1 month ago

Sounds reasonable.

Matz.

Updated by knu (Akinori MUSHA) about 1 month ago

  • Status changed from Open to Closed

Merged with r67211.

Also available in: Atom PDF