How to “unflatten” a Ruby Array?

前端 未结 5 1505
名媛妹妹
名媛妹妹 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] }
    
    0 讨论(0)
  • 2020-12-11 06:04

    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] }
    
    0 讨论(0)
  • 2020-12-11 06:08

    You could do:

    [5, 7, 8, 1].collect { |i| [i] }
    
    0 讨论(0)
  • 2020-12-11 06:11

    In point-free style:

    [5, 7, 8, 1].map(&method(:Array))
    
    0 讨论(0)
  • 2020-12-11 06:12

    Try this:

    [5, 7, 8, 1].map {|e| [e]}
    
    0 讨论(0)
提交回复
热议问题