Skip to content

Welcome to Tech by Example

Menu
  • Home
  • Posts
  • System Design Questions
Menu

Delete a nested key in a hash in Ruby Language

Posted on October 5, 2022October 5, 2022 by admin

Overview

It is possible to delete nested keys in a hash in Ruby Language.

Let’s see examples

One Level Nested Key

Here is the code to delete the key in a hash at the first level

sample = {
    "a" => "b",
    "c" => "d"
}
sample.delete("a")
puts sample

Output

{"c"=>"d"}

Two Level Nested Key

Here is the code to delete the key in a hash at the first level

sample = {
    "a" =>  {
        "b" => "c"
    }
    
}
sample["a"].delete("b")
puts sample

Output

{"a"=>{}}

Three Level Nested Key

Here is the code to delete the key in a hash at the first level

sample = {
    "a" =>  {
        "b" => {
            "c" => "d"
        }
    }
    
}
sample["a"]["b"].delete("c")
puts sample

Output

{"a"=>{"b"=>{}}}

Note: Check out our system design tutorial series System Design Questions

©2025 Welcome to Tech by Example | Design: Newspaperly WordPress Theme