From: Jano Svitok Date: 2007-05-05T14:06:47+09:00 Subject: Re: Why do these two code blocks have different behavior? On 5/5/07, yuricake wrote: > I am not a total newbie in ruby, but I am still hazy on how things > like blocks, proc objects and contexts work under the covers. I have > experience with Lisp lambdas, so feel free to get technical. > > 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 this return will jump out of the method altogether. So the method will print x once, and then return sum + x, that is 0 + 1 = 1 > } > end > > def q2 > @@a.inject(0) {|sum, x| > pp x > sum + x > } > end in this case, there's no return to interrupt the inject loop, so the sum will be calculated properly and return value from the method will be the return value of inject, i.e. the sum 6.