On Fri, 15 Dec 2000, Ben Tilly wrote:

> David Alan Black <dblack / candle.superlink.net> wrote:
> > > >
> > > >[1,2,3,4,5].map do |e| [e,-e] end .flatten
> > > >   => [1, -1, 2, -2, 3, -3, 4, -4, 5, -5]
> > > >
> > > I thought of that.  But if you want your output to be an
> > > array of arrays, it doesn't work right.
> >
> >Just don't .flatten it:
> >
> >[1,2,3,4,5].map do |e| [e,-e] end
> >   => [[1, -1], [2, -2], [3, -3], [4, -4], [5, -5]]
> >
> >(I thought the flattened version was more what you'd meant,
> >but anyway, either is possible.)
> 
> Um, what if you want to do your array with indices map
> on an array like the above?  .flatten is recursive, which
> means that a list of list of list of lists turns into a
> single list!

I'm not sure what it is you're saying wouldn't work.  For example:

a = [1,2,3,4,5]
b = a.map do |e| [e,-e] end 
c = b.map_with_indices do |e,i| "element #{i} is #{e.inspect}" end

p c[2]  # => "element 2 is [3, -3]"

The .flatten was only to illustrate (one version of) map (with a
little help :-) producing an array with more elements than the input
array.  (Are we talking past each other on some aspect of this?)

[...]

> >   (0...ary.size).map do |i| ... end
> >
> >which was the only way I could think of to iterate through indices
> >and return a mapping.  Anyway, as for the
> >
> >                  i, ary[i]
> >
> >part, I'm not sure why that can't be the return (exit?) value of an
> >iterator block, as it can for method definitions.  Then again...
> >when you
> >
> >        return a,b
> >
> >from a method, you are returning [a,b].
> >
> You answered your own question I think. :-)

Yes and no.  I probably should have written "In fact" rather than
"Then again", above.  My first line of thought was: since the method
syntax turns a,b into [a,b] anyway, it's no big deal that we have to
write [a,b] in the iterator block.  But I do wonder now why the same
a,b syntax isn't allowed in such a block (where it would return [a,b])
 -- no implications of non-Ruby-esque list behavior).


David

-- 
David Alan Black
home: dblack / candle.superlink.net
work: blackdav / shu.edu
Web:  http://pirate.shu.edu/~blackdav