From: "Gulyás Attila" Date: 2013-02-28T03:02:27+09:00 Subject: Re: Please, help (GCD) greatest common divisor. Thanks for taking the time to looking into it! I could figure out the boolean chain given the precedence but I thought that I am missing something obvious with "--p" because I couldn't twist more out of it in irb. ( ... and yes, my first thought was that p is being decremented but that made no sense:) I always found "inject" hard to grasp (my mind is like Pratchett's A'tuin when it comes to abstraction) and your example gives a new angle to chew on as I've never seen this approach before. Thanks! If you're interested in obfuscated code: http://mamememo.blogspot.hu/ (Yusuke Endoh's blog) I saved this for later because it's way over my head and he is writing one twisted code:) Thanks again. Attila On Wed, Feb 27, 2013 at 6:19 PM, Bartosz Dziewoński wrote: > 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 >