From: "Bartosz DziewoƄski" Date: 2013-02-28T02:19:30+09:00 Subject: Re: Please, help (GCD) greatest common divisor. Replying to the gist. > ### II. "inject"-part > # Breaking it down with [6,8] > gcd[[6,8]] #=> 2 > gcd=->(_){_.sort_by(&:-@).inject{|p,q|q.nonzero?&&gcd[[q,p-q]]||--p}} > # ( I am sure that I am missing something here ) > # 1st iteration: [8,6] -> 6 && gcd[[6,2]] || --8 > # 2nd iteration: [6,2] -> 6 && 2 && gcd[[2,4]] || --6 > # 3rd iteration: [4,2] -> 6 && 2 && 2 && gcd[[2,2]] || --4 > # 4th iteration: [2,2] -> 6 && 2 && 2 && 2 && gcd[[2,0]] || --2 > # 5th iteration: [2,0] -> 6 && 2 && 2 && 2 && nil && gcd[[0,2]] || --2 > # On the last iteration everything evaluates to nil before the ||.# (One remaining question: why --p?) #inject on a two-element array is essentially the same as splatting it in two separate variables. The following two snippets do the same thing: result = [1, 2].inject{|a, b| do_stuff_with(a, b) } a, b = *[1, 2] result = do_stuff_with(a, b) "a && b || c" is the same as "if a; b; else c; end" (or "a ? b : c"). This is a little abuse of the behavior of boolean operators :) "--p" is just for laughs. While this looks like decrementation in C / C++, it parses as "-(-p)" as is the same as simply "p". -- Matma Rex