From: Robert Klemme Date: 2006-02-02T06:54:01+09:00 Subject: Re: [RCR] Numeric#of Martin DeMello wrote: > Phil Duby wrote: >> >> I was looking for a clean (Ruby) way of creating an array of >> ascending integer values, with the final value zero. IE [ 1, 2, 3, >> 4, 0 ] >> i = 0; a = Array.new( 4 ) { i += 1 }.push 0 >> does what I want. > > (1..4).to_a.push(0) > > also Array.new passes in the index to the block, so you can do > > Array.new(4) {|i| i+1} Here are some more alternatives including a solution with the famous #inject. :-) >> a=Array.new(5) {|i| (i+1)%5} => [1, 2, 3, 4, 0] >> a=(1..4).to_a << 0 => [1, 2, 3, 4, 0] >> a=(1..5).inject([]) {|ar,i| ar << (i%5)} => [1, 2, 3, 4, 0] >> a=(1..5).inject([]) {|ar,i| ar << i} << 0 => [1, 2, 3, 4, 5, 0] Have fun! Kind regards robert