On May 5, 2007, at 12:45 AM, yuricake wrote:
> My question is - why do the following two functions have different
> behavior?
>
> require "pp"
>
> @@a = [1, 2, 3]
>
> def q1
> @@a.inject(0) {|sum, x|
>   pp x
>   return sum + x
> }
> end
>
> def q2
> @@a.inject(0) {|sum, x|
>   pp x
>   sum + x
> }
> end

Because the return statement terminates the method q1 and not the
block that is associated with the call to inject.  You are effectively
bailing out of inject on the first iteration.

In q2, when control runs off the end of the block, control is returned
to inject, which can continue with its iterations.

Gary Wright