From: hemant Date: 2006-10-20T23:33:12+09:00 Subject: Re: break from block On 10/20/06, Farrel Lifson wrote: > On 20/10/06, Michael Studman wrote: > > I'm not sure it's the Ruby way (I'm too new to Ruby to judge) but how > > about: > > > > block = lambda{|i| i > 5 ? throw(:enough) : nil} > > n = 10 > > > > catch(:enough) do > > n.times &block > > end > > > > > > > I've just run into the following problem. Doing this: > > > block = lambda{|i| i > 5 ? break : nil} > > > n.times &block > > > raises a LocalJumpError, I assume because break is not valid from > > > within a Proc object. Is there any way to get around this? > > > > > > Farrel > > > > > > > > I tried that but it's a performance killer (nearly 3 times as slow in > my informal testing), which I'm trying to optimise for atm. > > Farrel > > I think i got the error Farrel: http://www.ruby-doc.org/core/classes/LocalJumpError.html when you call 10.times {|i| break if i>5; p i}, it works because its not the one object that is being passed around, but when you pass pass a proc object to as an block to the method call, its initialized only once and once you do a break from the proc, subsequent calls fail because of LocalJumpError, because proc was terminated by :break( and will get terminated by :redo, :retry, :next, :return, or :noreason.) -- There was only one Road; that it was like a great river: its springs were at every doorstep, and every path was its tributary.