【问题标题】:How to flatten an array of arrays - but not all the way down如何展平数组 - 但不是一直向下
【发布时间】:2011-08-02 12:39:55
【问题描述】:

什么是最好的转换方式

[[["Club three Team one", 7800], ["Club three Team two", 7801]], [], [["Club four Team one", 7807], ["Club four Team two", 7808]], []]

进入

[["Club three Team one", 7800], ["Club three Team two", 7801], ["Club four Team one", 7807], ["Club four Team two", 7808]]

在红宝石中? flatten 将其一直转换为

["Club three Team one", 7303, "Club three Team two", 7304, "Club four Team one", 7310, "Club four Team two", 7311]

【问题讨论】:

    标签: ruby-on-rails ruby


    【解决方案1】:

    使用flatten(1)http://apidock.com/ruby/Array/flatten

    your_array = [[["Club three Team one", 7800], ["Club three Team two", 7801]], [], [["Club four Team one", 7807], ["Club four Team two", 7808]], []]
    your_array.flatten(1)
    #=> [["Club three Team one", 7800], ["Club three Team two", 7801], ["Club four Team one", 7807], ["Club four Team two", 7808]]
    

    【讨论】:

    • 可能值得注意的是,对于旧 Ruby 版本:your_array.inject([], :concat)
    • @tokland 对于大型阵列,它会慢得多
    • @fl00r:Array#concat 在 Ruby 中是就地的,所以它应该不会慢很多。我做了一些测试,它的性能几乎相同。
    • @tokland 我认为inject 是最慢的部分:)
    猜你喜欢
    • 2013-11-06
    • 1970-01-01
    • 1970-01-01
    • 2020-02-09
    • 2022-08-02
    • 2013-02-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多