From: Paul Brannan Date: 2002-03-27T04:38:23+09:00 Subject: Re: yield in iterator's body - On Tue, Mar 26, 2002 at 07:47:10PM +0900, 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 | ... I don't think you can do it with yield, but you can do it by passing the proc as a parameter: a = [1, 2, 3] p1 = proc { |p, x| p.call(x) } p2 = proc { |x| puts x } a.each { |x| p1.call(p2, x) } #=> prints "1\n2\n3\n" and returns a The problem is that when you use "yield", it uses the block that was given to the method you are currently executing, and not the block that was given to the call to the proc: def foo(a) p1 = proc { |x| yield x } p2 = proc { |x| puts "p2 says: #{x}" } a.each { |x| p1.call(x, &p2) } end a = [1, 2, 3] p foo(a) { |x| puts "foo says: #{x}" } #=> foo says: 1 #=> foo says: 2 #=> foo says: 3 #=> [1, 2, 3] I recently ran into this problem myself when I wanted to write a function that I wanted to work with both Methods and Procs (and any other object that responds to call(). The code would work in most cases, but didn't quite work with Procs. Perhaps there is or should be a way to unbind and then rebind a Proc? Paul