From: Benoit Daloze <eregontp@...>
Date: 2010-05-02T19:20:41+09:00
Subject: [ruby-core:29931] Re: [Feature #3232] Loops (while/until) should 	return last statement value if any, like if/unless

On 2 May 2010 01:56, Yukihiro Matsumoto <matz@ruby-lang.org> wrote:
> Hi,
>
> The last evaluated expression in this case is "i < 3", so the loop
> statement would have the return value of false value, even if it would
> return the *last* value.
>
> � � � � � � � � � � � � � � � � � � � � � � � � � � � �matz.

My bad, I forgot about condition evaluation.
But that result is really not interesting, as it will always be false
(or true for until).

Is is possible, then, to keep the result of the last expression in the
loop, before it fails?

>It returns the argument of break:
>x = while true; break 123; end  #=> 123
>If you don't break out of the loop it makes sense that the result is nil.

Sure, so a way to solve my example would be:

i = 0
loop do
  i += 1
  break "return value" unless i < 3
end #=> "return value"

But there are a few disadvantages to use this way:
- using 'loop' and 'break', while you perfectly now when you want to stop
- therefore you need an 'unless', or the negative condition of what
you expected to write after while/until
- you need to specify again explicitly the return value to break, so
you don't use any shortcut.

But my example is not clear, let's see this one:

def method
  array = []
  while <condition>
    array << do_sth
    # With loop & break, here would be: break array unless <condition>
  end
  array # I would like to remove this "superfluous" statement
end

This would be a nice feature, and would remove the need to explicitly
mention the return value, again after the loop.

I think it would be more consistent with if/unless
(even if that case is simpler because it is actually the last
evaluated expression).

It would be a kind of inject/each_with_object, but with a condition
instead of an Enumerable (and no initial value).

B.D.