user987266
user987266

Reputation:

Deep delete from Ruby hash by dotted path

Given such hash with nested hashes in Ruby (deep may vary):

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."
           }
         }
       }

How can I delete key and all its children values using simple "dotted" notation? Something like:

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

Upvotes: 5

Views: 884

Answers (1)

Yossi
Yossi

Reputation: 12110

path = path.split '.'
leaf = path.pop

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

Upvotes: 7

Related Questions