开发者

How to "unflatten" a Ruby Array?

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 }.col开发者_JAVA技巧lect { |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] }


In point-free style:

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


Try this:

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


There's nothing specifically wrong with what you're doing. I think they mean that to_a for a FixNum will be deprecated sometime in the future, which makes sense cause it's ambiguous what exactly to_a for a FixNum should do.

You could rewrite your line like this which would eliminate the error:

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


You could do:

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜