"David A. Black" <dblack / wobblini.net> schrieb im Newsbeitrag news:Pine.LNX.4.44.0412051338420.27774-100000 / wobblini... > Hi -- > > On Mon, 6 Dec 2004, Florian Gross wrote: > > > Robert Klemme wrote: > > > > >> Thoughts? When do you use the 'yield' statement in code? > > > More generally when you don't need direct access to the block given and > > > when you don't need to forward it to another method call. I think yield > > > is faster than the block form also. > > > > But note that you can also forward blocks without using the &block syntax: > > > > irb(main):022:0> def five_times > > irb(main):023:1> 5.times { |index| yield index } > > irb(main):024:1> end > > => nil > > irb(main):025:0> five_times { |i| puts "Hello ##{i}" } > > Hello #0 > > Hello #1 > > Hello #2 > > Hello #3 > > Hello #4 > > > > I'd expect this to be slower than the &block syntax, but I have not > > benchmarked it. Maybe the &block syntax is also less clutter to look at > > and thus easier to understand. 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 bm(20) do |b| b.report("yield") do bl_yield(REP) {|i| i + 1} end b.report("block") do bl_fwd(REP) {|i| i + 1} end end 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 Kind regards robert