From: Joel VanderWerf Date: 2002-03-27T02:39:43+09:00 Subject: Re: yield in iterator's body - Wladimir Mutel wrote: > > Can we write in Ruby something like this : > > a1.each { |f| ... yield f } { |g| ... yield g } ... > > i.e. to pipe one iterator body over another like we do pipes in Unix > shell ? > > cat a1 | ... echo a2 | ... echo a3 | ... One approach is in http://www.ruby-lang.org/en/raa-list.rhtml?name=Enumerable+tools Example: (10..14).pipe {|x| x+1}.pipe {|y| y.to_s}.pipe(:concat,"foo").to_a ==> ["11foo", "12foo", "13foo", "14foo", "15foo"] Note that the return value of each pipe call is not an array, but a proxy which supports the Enumerable interface. This has the advantage of not computing all the intermediate arrays. But you have to remember to convert to an array at the end, if you want an array. You can also use "for" without the to_a: for x in (10..14).pipe {|x| x+1}.pipe {|y| y.to_s}.pipe(:concat,"foo") ... end The last pipe is like #send, with a method name and args instead of a block.