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
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] }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With