From: Martin DeMello Date: 2003-01-22T02:17:08+09:00 Subject: Re: Ruby idiom (0...(expr)).map Gavin Sinclair wrote: > On Wednesday, January 22, 2003, 2:36:50 AM, Martin 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? > > I vaguely remember this idiom. Can you expand on its use? I think it > may become outdated with 1.8 features. In general, making an array out of an integer sequence (in its most basic form, (0...10).to_a # => [0,1,2,3,4,5,6,7,8,9].) More usefully, Range#map is a shortcut for Range.to_a.map, but since I most commonly want to start from 0, I thought a further shortcut for (0...n).map would make my code prettier. Frinstance, here's a snippet from some code I'm currently writing to format text into columns: npages.times {|i| ranges.push((pagebreak * i)..(pagebreak*i+psize-1))} ranges.each {|r| page << r.map {|line| (0...ncols).map {|col| text[line + col*psize]}.join(col_sep) } } where I want an array each element of which is a function of the current index. Here it's not so bad, since I've already had occasion to define ncols, but if it were an inline expression, the code would start looking really messy. martin