From: "Joe Wölfel" Date: 2008-10-18T23:17:48+09:00 Subject: Re: Counting Don't need no stinkin' select either;) It's much faster if you don't iterate at all. n=1000 d = 10 (n+d)*(n/(d*2)) => 50500 The formula is all you need because 1000 + 10 = 1010 990 + 20 = 1010 etc. 50 times. The following select gives the same answer but is much slower. (1..n).select{|a| 0 == a % d }.inject {|sum, x| sum+x} => 50500 One caveat. The formula I gave assumes that 'n' is divisible by 'd'. It shouldn't be hard to change the formula so that isn't necessary though. Cheers, Joe On 18 oct. 08, at 08:39, William James wrote: > Tom Clarke wrote: > >> How would i go about making Ruby count to say 1000 usin only >> multiples >> of say 2 and 6. Then i am looking to add all of the outputted >> numbers. >> Can anyone help > > "We don't need no stinkin' loops!" > > (1..1000).select{|n| 0 == n % 10 } > ==> > [10, 20, 30, 40, 50, 60, 70, 80, 90, 100, 110, 120, 130, 140, > 150, 160, 170, 180, 190, 200, 210, 220, 230, 240, 250, 260, 270, > 280, 290, 300, 310, 320, 330, 340, 350, 360, 370, 380, 390, 400, > 410, 420, 430, 440, 450, 460, 470, 480, 490, 500, 510, 520, 530, > 540, 550, 560, 570, 580, 590, 600, 610, 620, 630, 640, 650, 660, > 670, 680, 690, 700, 710, 720, 730, 740, 750, 760, 770, 780, 790, > 800, 810, 820, 830, 840, 850, 860, 870, 880, 890, 900, 910, 920, > 930, 940, 950, 960, 970, 980, 990, 1000] > > -- > >