How to “unflatten” a Ruby Array?

前端 未结 5 1513
名媛妹妹
名媛妹妹 2020-12-11 05:39

I am currently trying to convert this ruby array:

[5, 7, 8, 1]

into this:

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

What\'s th

5条回答
  •  攒了一身酷
    2020-12-11 06:04

    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] }
    

提交回复
热议问题