How to increase flexibility of #flatten

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?

···

--
Posted via http://www.ruby-forum.com/\.

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)

···

On 5 February 2013 11:03, Tom Stut <lists@ruby-forum.com> 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?

--
  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

Nice discussion,would like to participate here.

Thanks

···

--
Posted via http://www.ruby-forum.com/.

First stab:

    def deflate(a)
       a.inject([]){ |c,e| (Array === e ? (Array === e.first ? c.concat(e)
: c << e) : c << e); c }
    end

Doesn't handle deeper nestings though.

Then contribute something **meaningful**.

···

Am 05.02.2013 07:52, schrieb Love U Ruby:

Nice discussion,would like to participate here.

Thanks

--
<https://github.com/stomar/&gt;

Please go ahead.

Cheers

robert

PS: Please do not use the forum to set your personal reading markers.
If you need those you can always use bookmarks for that.

···

On Tue, Feb 5, 2013 at 7:52 AM, Love U Ruby <lists@ruby-forum.com> wrote:

Nice discussion,would like to participate here.

--
remember.guy do |as, often| as.you_can - without end
http://blog.rubybestpractices.com/