class Enumerable

instance method

Enumerable#pipe filter_spec = nil, *args, &filter_proc

Can be used to "pipe" an Enumerable sequence through a filter.

Enumerable#pipe returns an Enumerable object whose each method iterates over self and applies a filter to each enumerated object, as specified by the arguments. Only the current element of the sequence is kept in memory.

If filter_spec is a string or symbol, filter_proc is ignored and filter_spec is treated as a method name. This method name is sent, along with arguments args, to each element of the sequence being enumerated.

If filter_spec is anything else, except nil, filter_proc is ignored and filter_spec is required to be an object that responds to [], such as a proc or a hash. The [] method of filter_spec is called with each element of the sequence in turn as an argument, along with args.

If next_spec is not given, or is nil, a block is required. In this case, iteration proceeds as in the preceding paragraph.

Using #pipe has potential performance advantages. The iteration

e.collect { |x| x.m }.each { |y| ... }

can be rewritten as

e.pipe(:m).each { |y| ... }

which doesn't generate an intermediate array, and uses a send instead of a proc call. Of course, it could also be written as

e.each { |x| y = x.m ... }

but that may be undesirable for readability or because the block is to be taken from a proc contained in a variable:

pr = proc { ... }
e.pipe(:m).each &pr

Also, chains of collect and select, such as

(1..100).collect { |x| x**2 }.select { |y| y > 1000 && y < 2000 }

can't be easily rewritten as a single select.


require 'enum/pipe'

[0,1,2,3,4].pipe { |x| x + 1 }.each { |x|
  print x, " "

# prints: 1 2 3 4 5

stooges = ['lARRY', 'cURLY', 'mOE']
p stooges.pipe(:swapcase).reject { |x| x =~ /url/ }
p stooges.pipe(:tr, 'RlcOEL', 'gBboog').pipe(:capitalize).entries

# prints:  ["Larry", "Moe"]
#          ["Baggy", "Buggy", "Moo"]


Enumerable tools 1.5

The current version of this software can be found at .


This software is distributed under the Ruby license. See


Joel VanderWerf,