From: Mark Hubbart Date: 2004-03-13T05:44:39+09:00 Subject: Re: iterating with multiple values On Mar 12, 2004, at 10:09 AM, gabriele renzi wrote: > I thought this should work: > [1,2,3,4,5,6].inject do |pre2,cur| > print pre2[0],pre2[1],cur,"\n" > [pre2[1],cur] > end > > but it gives strange results in the first loops. > 102 > 023 > 234 > 345 > 456 to get an idea of why it doesn't work, try this: [1,2,3,4,5,6].inject do |pre2,cur| print pre2[0],pre2[1],cur," :: ",pre2.inspect,cur.inspect,"\n" [pre2[1],cur] end output: 102 :: 12 023 :: [0, 2]3 234 :: [2, 3]4 345 :: [3, 4]5 456 :: [4, 5]6 pre2 is not an array on the first pass. Also, unless you pass an argument to #inject, on the first loop, it passes in the first two values. Try this: [1,2,3,4].inject([nil]*2) do |pre,cur| puts "%s,%s,%s" % (pre + [cur]) pre.slice(1..-1) + [cur] end ,,1 ,1,2 1,2,3 2,3,4 If you pass an array of nils, it works the way you might expect. Also, this is scalable; you can multiply [nil] by a larger number to capture more previous variables: (1..8).to_a.inject([nil]*4) do |pre,cur| puts "%s,%s,%s,%s,%s" % (pre + [cur]) pre.slice(1..-1) + [cur] end ,,,,1 ,,,1,2 ,,1,2,3 ,1,2,3,4 1,2,3,4,5 2,3,4,5,6 3,4,5,6,7 4,5,6,7,8 --Mark