From: "David A. Black" Date: 2004-12-08T04:19:11+09:00 Subject: Re: Using yield Hi -- On Tue, 7 Dec 2004, Robert Klemme wrote: > 13:21:36 [robert.klemme]: ruby yield-vs-block.rb > user system total real > yield 0.250000 0.000000 0.250000 ( 0.249000) > block 0.125000 0.000000 0.125000 ( 0.124000) > 13:21:44 [robert.klemme]: cat yield-vs-block.rb > > require 'benchmark' > include Benchmark > > REP = 100000 > > def bl_yield(n) > n.times {|i| yield i} > end > > def bl_fwd(n,&b) > n.times(&b) > end Those aren't equivalent, though. The second one would have to be: n.times {|i| b.call(i) } to compare the two idioms directly. When I make that change I get: yield 0.320000 0.000000 0.320000 ( 0.332194) block 0.460000 0.000000 0.460000 ( 0.490299) > I blieve the yield forwarding is slower because there is one more call. > > > Wouldn't the &block form be more clutter? Well, not that it's so > > much clutter in either case, but I think it would be slightly wordier > > (def five_time(&block) etc.) > > For forwarding I prefer &b because the original block is simply passed on > vs. a new block yields to the original block. That seems awkward to me > and seems to be slower, too. Personally I find the yield forwarding more > clutter. YMMV The clutter point was (at least in my mind :-) strictly about the difference between: def x yield end and def x(&b) b.call end As for forwarding a block to a new method -- isn't &b the only way? Or am I behind the times on automatic propagation? (But even in that case I don't think supplying block #1 to method #2 is the same as yielding to block #1 during method #1.) David -- David A. Black dblack@wobblini.net