From: Kirk Haines Date: 2009-11-26T01:49:31+09:00 Subject: Re: Ruby internals & other questions --00032555aa167261b3047934d76e Content-Type: text/plain; charset=ISO-8859-1 On Wed, Nov 25, 2009 at 9:29 AM, Aldric Giacomoni wrote: > Ralph Shnelvar wrote: > > > > y=0 > > 1_000_000.times {|x| y+=x} > > y = (1..1_000_000).inject { |a, b| a + b } > > More idiomatic, though maybe yours is easier to read at first. > Ugh. His, while wrong for what he is trying to do (sum from 1 to 1000000) is vastly superior to using inject like that. It's not idiomatic. It's obtuse. If one really wants to figure it out iteratively: y = 0; 1.upto(1000000) {|x| y += x} or y = 0; (1..1000000).each {|x| y += x} Are both easier to read at first, at second, and at 1000000 viewings than using inject is. Additionally, inject has no advantage with regard to either execution speed or object creation (less object creation is generally better). There is no point in using it in a case like this. Inject is whiz-bang cool, and sometimes seems like an elegant solution, but it usually makes code slower and harder to read when people use it. Kirk Haines --00032555aa167261b3047934d76e--