How to "unflatten" Ruby Array?

I am currently trying to convert this ruby ​​array:

[5, 7, 8, 1] 

in it:

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

What is the best way?

I am currently doing it like this:

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

But I get the following errors:

warning: by default, `to_a 'will be deprecated

What am I doing wrong? Could you advise how to do it right?

Thanks in advance and best regards!

+6
source share
5 answers

The shortest and fastest solution uses Array#zip :

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

Another nice way: transpose :

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

The most intuitive way, probably, is that @Thom offers:

 values.map{|e| [e] } 
+28
source

In the dissolute style:

 [5, 7, 8, 1].map(&method(:Array)) 
+17
source

Try the following:

 [5, 7, 8, 1].map {|e| [e]} 
+11
source

There is nothing special in what you do. I think they mean that to_a for FixNum will become obsolete sometime in the future, which makes sense to make it ambiguous, what exactly to_a for FixNum should do.

You can rewrite your line to fix this error:

 [5, 7, 8, 1].select { |element| element }.collect { |element| [element] } 
+3
source

You can do:

 [5, 7, 8, 1].collect { |i| [i] } 
+1
source

Source: https://habr.com/ru/post/894417/


All Articles