Christopher Brown
10/20/2006 3:35:00 PM
-----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA1
On 20 Oct 2006, at 4:37 PM, Farrel Lifson wrote:
> On 20/10/06, Robert Klemme <shortcutter@googlemail.com> wrote:
>> On 20.10.2006 15:45, Farrel Lifson wrote:
>> > 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?
>>
>> The direct form works.
>>
>> irb(main):008:0> 10.times {|i| p i; break if i > 5}
>> 0
>> 1
>> 2
>> 3
>> 4
>> 5
>> 6
>> => nil
>>
>> Hm, at the moment I do not have an idea. What do you need that for?
>> Maybe there is a different solution. For example:
>>
>> irb(main):009:0> crit = lambda {|i| i > 5}
>> => #<Proc:0x00395698@(irb):9>
>> irb(main):010:0> 10.times {|i| p i; break if crit[i]}
>> 0
>> 1
>> 2
>> 3
>> 4
>> 5
>> 6
>> => nil
>>
>> Cheers
>>
>> robert
>
> I'm just trying to optimise some code and I was wondering if doing
> block = lambda{|i| #processing; if i > 5; break}
> n.times &block
> would be any faster than doing it directly.
>
> Farrel
>
On a tangential note, I'd be worried about the not-so-obvious flow
control.
Why not make the block a boolean predicate and do all the flow
control from inside the loop?
irb(main):022:0> 10.times do |i|
irb(main):023:1* break unless block.call i
irb(main):024:1> p i
irb(main):025:1> end
Now the flow control is based on evaluation obvious to the looping
construct and the contract for the block is "returns boolean".
If the block alters the flow control, it's much less clear. In the
case above, you know when "p i" is going to be skipped. If the block
breaks, it's not clear.
Cheers,
Chris
-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.4.3 (Darwin)
iD8DBQFFOOynrOGxDZoCCzURApcyAKDrtZIjBzxMXGQDzbGy29O0QpvxCwCgytLK
SaG82KxwSV3lIz+iDP8LPq0=
=7ItU
-----END PGP SIGNATURE-----