73

What's the best way to convert this

[[["Club three Team one", 7800], ["Club three Team two", 7801]], [], [["Club four Team one", 7807], ["Club four Team two", 7808]], []]

into

[["Club three Team one", 7800], ["Club three Team two", 7801], ["Club four Team one", 7807], ["Club four Team two", 7808]]

in ruby? flatten converts this all the way down to

["Club three Team one", 7303, "Club three Team two", 7304, "Club four Team one", 7310, "Club four Team two", 7311]

1 Answer 1

125

use flatten(1) http://apidock.com/ruby/Array/flatten

your_array = [[["Club three Team one", 7800], ["Club three Team two", 7801]], [], [["Club four Team one", 7807], ["Club four Team two", 7808]], []]
your_array.flatten(1)
#=> [["Club three Team one", 7800], ["Club three Team two", 7801], ["Club four Team one", 7807], ["Club four Team two", 7808]]
Sign up to request clarification or add additional context in comments.

4 Comments

it may be worth noting, for older Ruby versions: your_array.inject([], :concat)
@tokland for big arrays it would be much slower
@fl00r: Array#concat is in-place in Ruby, so it shouldn't be much slower. I made some tests and it's pretty much the same performance.
@tokland I think that inject is slowest part :)

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.