From: Matthew Kerwin Date: 2013-02-05T11:23:23+09:00 Subject: Re: How to increase flexibility of #flatten --f46d042f9f9a7c3faa04d4f0e38b Content-Type: text/plain; charset=ISO-8859-1 On 5 February 2013 11:03, Tom Stut wrote: > I am trying to use flatten to change > > #this > => [ [1, 3], [1, 4], [2, 3], [2, 4], [ [5, 5], [6, 6] ] ] > #to this. > => [ [1,3], [1,4], [2,3], [2,4], [5,5], [6,6] ] > > I've tried giving flatten an argument of 1, but it removes dimensions > that I want to remain. > > >> x.flatten(1) > => [1, 3, 1, 4, 2, 3, 2, 4, [5, 5], [6, 6] ] > > is there a way to iterate through that first array to produce the output > I want using flatten? > Do you want a general solution that will always reduce things down the the inner-most array? And is there no limit to how many levels deep those inner-most arrays will be? If so, you'd probably need a recursive function call. Note that if all the inner-most arrays have exactly two elements, you can use: my_array.flatten.each_slice(2).to_a (the .to_a is to collapse the Enumerator back to actual data; not really necessary most of the time) -- Matthew Kerwin, B.Sc (CompSci) (Hons) http://matthew.kerwin.net.au/ ABN: 59-013-727-651 "You'll never find a programming language that frees you from the burden of clarifying your ideas." - xkcd --f46d042f9f9a7c3faa04d4f0e38b Content-Type: text/html; charset=ISO-8859-1 Content-Transfer-Encoding: quoted-printable
On 5 February 2013 11:03, Tom S= tut <lists@ruby-forum.com> wrote:
I am trying to use flatten to change

#this
=3D> [ [1, 3], [1, 4], [2, 3], [2, 4], [ [5, 5], [6, 6] ] ]
#to this.
=3D> [ [1,3], [1,4], [2,3], [2,4], [5,5], [6,6] ]

I've tried giving flatten an argument of 1, but it removes dimensions that I want to remain.

>> x.flatten(1)
=3D> [1, 3, 1, 4, 2, 3, 2, 4, [5, 5], [6, 6] ]

is there a way to iterate through that first array to produce the output I want using flatten?

=
Do you want a general solution that will always reduce things down th= e the inner-most array? =A0And is there no limit to how many levels deep th= ose inner-most arrays will be? =A0If so, you'd probably need a recursiv= e function call.

Note that if all the inner-most arrays have exactly two elem= ents, you can use:
=A0 =A0 my_array.flatten.each_slice(2).to_a

(the .to_a is to collapse the Enumerator back = to actual data; not really necessary most of the time)

--
=A0 Matthew Kerwin, B.Sc (CompSci) (Hons)
=A0 http://matthew.kerw= in.net.au/
=A0 ABN: 59-013-727-651

=A0 "You'll never= find a programming language that frees
=A0 you from the burden of clarifying your ideas." - xkcd
--f46d042f9f9a7c3faa04d4f0e38b--