【问题标题】:Rails flatten quick导轨快速变平
【发布时间】:2014-05-29 15:27:23
【问题描述】:

我正在从 YAML 文件加载配置。

我有一个看起来像这样的哈希:{:first=>{:abc=>[["one", "two", "three"]], :def => [["one", "two", "three"]]}, :second=>{:abc=>[["one", "two", "three"]]}}

但我想得到:

{:first=>{:abc=>["one", "two", "three"], :def => ["one", "two", "three"]}, :second=>{:abc=>["one", "two", "three"]}}

即展平末端阵列。 结构不会比此处显示的“更深”。

单行代码是首选。

【问题讨论】:

    标签: ruby-on-rails ruby arrays hash flatten


    【解决方案1】:

    这应该可行:

    hash.each_value do |nested_hash|
      nested_hash.each_value do |array|
        array.flatten!
      end
    end
    

    或者,在单行版本中:

    hash.each_value { |nested_hash| nested_hash.each_value(&:flatten!) }
    

    【讨论】:

      猜你喜欢
      • 2015-01-25
      • 2016-11-20
      • 1970-01-01
      • 2019-02-17
      • 2014-10-02
      • 2010-11-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多