【问题标题】:Deep delete from Ruby hash by dotted path通过虚线路径从 Ruby 哈希中深度删除
【发布时间】:2013-06-19 20:48:21
【问题描述】:

在 Ruby 中给定这样的带有嵌套哈希的哈希(深度可能会有所不同):

hash = {"status_message"=>
         { "destination_does_not_exist"=>
           {"message_header"    => "Zielordner existiert nicht",
            "message_body"      => "Der Zielordner für das Backup existiert nicht mehr.",
            "corrective_action" => "Erstellen Sie den Zielordner."
           }
         }
       }

如何使用简单的“点”表示法删除键及其所有子值? 类似的东西:

path = "status_message.destination_does_not_exist.message_header"
hash.delete!(path)

【问题讨论】:

标签: ruby


【解决方案1】:
path = path.split '.'
leaf = path.pop

path.inject(hash) {|h, el| h[el]}.delete leaf

【讨论】:

  • 很好,谢谢。我刚学 ruby​​,所以没认出这是一棵简单的树。
  • Yossi,可能有一些关于使用 Ruby 操作树的信息吗?如何使用哈希等表示它们/
  • 从未见过任何相关资源,抱歉。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-05-25
  • 2020-12-13
  • 2011-04-19
  • 1970-01-01
  • 2016-10-31
  • 1970-01-01
相关资源
最近更新 更多