From: Dave Thomas Date: 2000-09-03T21:53:05+09:00 Subject: [ruby-talk:4761] Re: Piping in Ruby? Stephen White writes: > > Could you give an example of how you'd use this in Ruby? > > Another example (just tried to do this now) is filtering output: > > list.each {|i| puts i } | grep "fred" > ^^^^^^^^^^^^^ ... > a = [] > list.scan(pattern) {|i| a << convert(i) } > a.each {|i| code } > The trick in both of these cases is to keep your data in array format until the last minute. In the first case, the 'puts' will have written the data out, so it is too late to access it directly. You _could_ do it the way shell do, and create sub-processes and pipes, but why not just do: list = %w(bert fred andy fredeerick) list.grep(/fred/).each {|i| puts i} or use a side-effect: list.grep(/fred/) { |i| puts i } In the second case, the trick is the collect method: list.grep(/fred/).collect {|i| convert(i)} .each {|i| code... } Collect takes an enumerable collection and returns a new array where each element is some mapping of the original collection. You can then further process that resulting array. In the example above I've used 'each', just as you did in your original. In reality, you can keep expanding this array pipeline indefinitely list.collect {|i| doThing1(i) } . collect {|i| doThing2(i) } . collect {|i| doThing3(i) } . collect {|i| doThing4(i) } . collect {|i| doThing5(i) } ... etc Regards Dave