Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to "unflatten" a Ruby Array?

Tags:

arrays

ruby

I am currently trying to convert this ruby array:

[5, 7, 8, 1]

into this:

[[5], [7], [8], [1]]

I am currently doing it like this:

[5, 7, 8, 1].select { |element| element }.collect { |element| element.to_a }

but I'm getting the following warning:

warning: default `to_a' will be obsolete
like image 201
jlstr Avatar asked Aug 05 '11 21:08

jlstr


1 Answers

The shortest and fastest solution is using Array#zip:

values = [5, 7, 8, 1]
values.zip # => [[5], [7], [8], [1]]

Another cute way is using transpose:

[values].transpose # =>  [[5], [7], [8], [1]]

The most intuitive way is probably what @Thom suggests:

values.map { |e| [e] }
like image 115
Marc-André Lafortune Avatar answered Oct 03 '22 02:10

Marc-André Lafortune