On Nov 14, 4:46=A0am, w_a_x_man <w_a_x_... / yahoo.com> wrote:
> On Nov 14, 2:54=A0am, timr <timra... / gmail.com> wrote:
>
>
>
>
>
>
>
>
>
> > This code works because 'exit' within the lambda within the block
> > stops the loop. However, I don't want to stop the program. I need to
> > use break rather than exit. But break won't work within that lambda--
> > the loop doesn't stop. I can of course reorganize the statement so
> > that it isn't a terse one-liner, and get it to work. But I would like
> > to be able to break the loop from within that lambda function if it is
> > possible. =A0Somehow, I guess I need to make that break have a binding
> > to the method. Any ideas?!?
>
> > def solve_by_iter
> > =A0 counter =3D 1
> > =A0 loop do
> > =A0 =A0 yield counter
> > =A0 =A0 counter +=3D 1
> > =A0 end
> > end
> > solve_by_iter { |test| =A0lambda{puts test; exit}.call if (1..6).all?{|
> > num| test%num =3D=3D (num-1)} }
> > #I want to use: solve_by_iter { |test| =A0lambda{puts test; break}.call
> > if (1..6).all?{|num| test%num =3D=3D (num-1)} }
>
> solve_by_iter{|test|
> =A0 if (1..6).all?{|num| test % num =3D=3D num - 1 }
> =A0 =A0 puts test
> =A0 =A0 break
> =A0 end
>
> }
>
> solve_by_iter{|test|
> =A0 (1..6).all?{|num| test%num =3D=3D num-1} and (puts test; break)
>

That is also a clever solution. It uses 'and' for its ability control
whether a second statement should be evaluated rather than its boolean
sense. And I hadn't seen parentheses used to create multiline
statements like this before. That is the only reason I had been using
lambda before--to get a block of code with more than one line to be
executed as a single unit.

Similarly, break() is useful as previously suggested. The break() also
removes the need for a lambda statement. Combining solutions, and
using the if statement rather than 'and' which in my mind is slightly
easier to read, how about this (w/ slight refactoring of variable
names):

def solve_by_iter
counter =3D 1
 loop do
   yield(counter)
   counter+=3D1
 end
end

solve_by_iter{|numer| (puts numer; break) if (1..6).all?{|denom| numer
%denom =3D=3D denom-1}}

Thanks guys, I learned a lot from your responses to this post.
Tim