From: ahoward Date: 2003-01-25T02:49:14+09:00 Subject: Re: Ruby idiom (0...(expr)).map On Fri, 24 Jan 2003, Bulat Ziganshin wrote: > Hello ahoward, > > Tuesday, January 21, 2003, 8:57:22 PM, you wrote: > > >> > I've found myself writing (0...(expr)).map (as an alternative to > >> > a = []; expr.times {|i| a << ..}) often enough that I was wondering > >> > whether to define it as a method of fixnum. Fixnum#map doesn't seem > >> > quite right, though - any name suggestions? > > may be > > Array.new(expr) {|i| i} i didn't actually write that post, but i've been thinking of simply having new/initialize take a block... something like this : class Array def self.init n = 0, o = nil, &b if b a = new n n.times {|i| a[i] = o ? b.call(o) : b.call(i)} a else self.new n, o end end end if $0 == __FILE__ ary = [0,1,2] p Array.init 1, 42 # >> [42] p Array.init (3, []) {|a| a.clone} # >> [[], [], []] p Array.init (3, ary) {|a| a.pop} # >> [2, 1, 0] p Array.init (4) {|i| i} # >> [0, 1, 2, 3] p Array.init (2) {[rand]} # >> [[0.3466412831], [0.7881289076]] end if a default object is given, the block is called with that object, otherwise the block is called with the index being initialized .... someone will fill this in ;-) ... -a -- ==================================== | Ara Howard | NOAA Forecast Systems Laboratory | Information and Technology Services | Data Systems Group | R/FST 325 Broadway | Boulder, CO 80305-3328 | Email: ahoward@fsl.noaa.gov | Phone: 303-497-7238 | Fax: 303-497-7259 ====================================