Feature #707
Documentation for Enumerator chaining
| Status: | Assigned | Start date: | 11/03/2008 | |
|---|---|---|---|---|
| Priority: | Low | Due date: | ||
| Assignee: | % Done: | 0% |
||
| Category: | DOC | |||
| Target version: | 2.0.0 |
Description
Enumerators now support a horizontal filter/chaining pattern:
generator.filter1 { ... }.filter2 { ... }.filter3 { ... }.consumer
The overall pattern for a filter is:
Enumerator.new do |y|
source.each do |input| # filter INPUT
...
y << output # filter OUTPUT
end
end
This is extremely powerful. However it is not obvious to the newcomer that this is even possible. (Confusion may arise where people know Ruby 1.8's Enumerator, which cannot do this)
So I would just like to see this pattern documented with an example, e.g. under ri Enumerator.new
I have attached a possible example. Note that I have written my Fib generator in a style familiar from ruby-1.8, to emphasise that the Enumerator filter doesn't require a specially-written generator.
History
Updated by Brian Candler over 3 years ago
Here is another (shorter and simpler)
class Enumerator
def filter(&blk)
self.class.new do |y|
each do |*input|
blk.call(y, *input)
end
end
end
end
a = (1..1_000_000_000).to_enum
a.filter { |out,inp| out << inp if inp % 2 == 0 }.
filter { |out,inp| out << inp+100 }.
with_index.each { |inp,c| puts inp; break if c > 10 }
Updated by Koichi Sasada about 3 years ago
- Assignee set to Yukihiro Matsumoto
Updated by Roger Pack about 2 years ago
Is this also possible in 1.8? http://www.ruby-forum.com/topic/198804#new http://github.com/trans/facets/blob/master/lib/core/facets/denumerable.rb Brian do you think you could write the tutorial on chaining started here: http://wiki.github.com/rdp/ruby_tutorials_core/enumerator ? -r
Updated by Brian Candler about 2 years ago
> Is this also possible in 1.8? Sure. Block-form Enumerator is surprisingly straightforward to implement, see http://github.com/trans/facets/blob/master/lib/more/facets/enumerator.rb But since 1.9 has it already, I think it's worth documenting the possibilities more clearly.
Updated by Shyouhei Urabe over 1 year ago
- Status changed from Open to Assigned