【问题标题】:Organize array of symbols and hashes组织符号和哈希数组
【发布时间】:2019-09-19 19:07:39
【问题描述】:

有没有更有效的方法?

items = [:one, :two, {three: 3}, {four: 4}, :five, :six]  # => [:one, :two, {:three=>3}, {:four=>4}, :five, :six]

symbols = items.select { |n| n.class == Symbol }              # => [:one, :two, :five, :six]
params = items.select { |n| n.class == Hash }.reduce(:merge)  # => {:three=>3, :four=>4}
symbols << params                                             # => [:one, :two, :five, :six, {:three=>3, :four=>4}]

【问题讨论】:

    标签: ruby-on-rails arrays ruby


    【解决方案1】:

    如果数组中只有 Symbols 和 Hashes,您可以使用 partition 并通过 2 个步骤获得相同的结果:

    s, h = items.partition {|i| i.class == Symbol}
    s << h.reduce(&:merge)
    #=> [:one, :two, :five, :six, {:three=>3, :four=>4}]
    

    【讨论】:

    • 还有什么可能吗?有没有办法只组织符号和哈希?
    • user2012677,在这种情况下写h, s = items.partition { |i| i.class == Hash }(第二行不变)。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-02-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-10-29
    相关资源
    最近更新 更多