user938363
user938363

Reputation: 10360

How to reduce the dimension of array in ruby

We have an array items like this:

items = [[[["2012-09-01", 10], ["2011-09-10", 20]]], [[["2010-01-01", 23]]]]

How to reduce the 4 dimensional items to 2 dimensional array like this:

items = [["2012-09-01", 10], ["2011-09-10", 20], ["2010-01-01", 23]]

Thanks so much.

Upvotes: 2

Views: 462

Answers (2)

JGrubb
JGrubb

Reputation: 889

Try Array#flatten. - http://www.ruby-doc.org/core-1.9.3/Array.html#method-i-flatten

irb(main):001:0> items = [[[["2012-09-01", 10], ["2011-09-10", 20]]], [[["2010-01-01", 23]]]]
=> [[[["2012-09-01", 10], ["2011-09-10", 20]]], [[["2010-01-01", 23]]]]
irb(main):002:0> items.flatten(2)
=> [["2012-09-01", 10], ["2011-09-10", 20], ["2010-01-01", 23]]

Upvotes: 5

David Lesches
David Lesches

Reputation: 788

Use Ruby's flatten method.

You can specify the level amount to flatten.

See http://www.ruby-doc.org/core-1.9.3/Array.html#method-i-flatten

Upvotes: 4

Related Questions