From: Eric Hodel Date: 2006-03-08T07:47:05+09:00 Subject: Re: Rescue on do end blocks On Mar 7, 2006, at 4:31 AM, Farrel Lifson wrote: > I've been playing around with rescue expressions and besides being put > on functions they also seem to work when defining classes (useful for > metaprogramming perhaps?) [...] > However, why can they not be applied to do end blocks? > > irb(main):016:0> [1,2,3].each do |num| > irb(main):017:1* num.upcase > irb(main):018:1> rescue > irb(main):019:1> puts "Error" > irb(main):020:1> ensure > irb(main):021:1* puts "Clened up" > irb(main):022:1> end > SyntaxError: compile error > (irb):18: syntax error > (irb):20: syntax error > from (irb):22 This will make blocks much more expensive to call because you'll have to perform the exception handler setup and teardown for each invocation of the block which will give a slight performance degradation: require 'benchmark' N = 10_000_000 Benchmark.bmbm do |bm| bm.report 'without begin' do N.times { 0 } end bm.report 'with begin' do N.times { begin 0 end } end bm.report 'with rescue' do N.times { begin 0; rescue; end } end end user system total real without begin 4.520000 0.020000 4.540000 ( 4.939785) with begin 5.000000 0.030000 5.030000 ( 6.050101) with rescue 6.720000 0.030000 6.750000 ( 7.716410) While having an implicit begin won't give the same level of slowdown if implemented in the compiler, there's no pressing need to add the complexity to Ruby because it isn't the common case. -- Eric Hodel - drbrain@segment7.net - http://blog.segment7.net This implementation is HODEL-HASH-9600 compliant http://trackmap.robotcoop.com