2

I wanted to reduce a multi-dimensional array into a smaller multi-dimensional array. Let me post what I mean. Here is my input/starting array:

[
  [
    [ ["Armando", "P"], ["Dave", "S"] ],
    [ ["Richard", "R"],  ["Michael", "S"] ],
  ],
  [
    [ ["Allen", "S"], ["Omer", "P"] ],
    [ ["David E.", "R"], ["Richard X.", "P"] ]
  ]
]

And I think this is the four dimensional array which I want to reduce to:

["Armando", "P"], ["Dave", "S"], ["Richard", "R"],  ["Michael", "S"], ["Allen", "S"],["Omer", "P"] , ["David E.", "R"], ["Richard X.", "P"] 

How can I do this in Ruby?

2
  • You can just loop through all these levels and build your result. Have you tried that? :) Commented Oct 21, 2012 at 10:37
  • @SergioTulentsev: But Array#flatten does it for you. Commented Oct 21, 2012 at 14:00

1 Answer 1

3

Use Array#flatten(levels):

xs.flatten(2)
Sign up to request clarification or add additional context in comments.

5 Comments

@tokland: This returns => ["Armando", "P", "Dave", "S", "Richard", "R", "Michael", "S", "Allen", "S", " Omer", "P", "David E.", "R", "Richard X.", "P"]
I want to maintain the last level !!
@CSSS: are you sure? I just tested it in a console, taking the array verbatim from your question, you need two flattenings. Anyway, check flatten(1).
Still there is some level of nesting that remains
Sorry.. my fault. Your solution is perfect !

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.