Forum: Ruby How to increase flexibility of #flatten

Posted by Tom Stut (tomst)
on 2013-02-05 02:02
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 by Matthew Kerwin (mattyk)
on 2013-02-05 03:28
(Received via mailing list)
On 5 February 2013 11:03, Tom Stut <lists@ruby-forum.com> wrote:

> >> 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
Posted by Love U Ruby (my-ruby)
on 2013-02-05 07:52
Nice discussion,would like to participate here.

Thanks
Posted by unknown (Guest)
on 2013-02-05 08:14
(Received via mailing list)
Am 05.02.2013 07:52, schrieb Love U Ruby:
> Nice discussion,would like to participate here.
>
> Thanks

Then contribute something **meaningful**.
Posted by Robert Klemme (robert_k78)
on 2013-02-05 08:56
(Received via mailing list)
On Tue, Feb 5, 2013 at 7:52 AM, Love U Ruby <lists@ruby-forum.com> 
wrote:
> Nice discussion,would like to participate here.

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.
Posted by Thomas Sawyer (7rans)
on 2013-02-06 01:55
(Received via mailing list)
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.
Please log in before posting. Registration is free and takes only a minute.
Existing account (Switch to SSL-encrypted connection)
NEW: Do you have a Google/GoogleMail or Yahoo account? No registration required!
Log in with Google account | Log in with Yahoo account
No account? Register here.