Yoann Augen
Yoann Augen

Reputation: 2036

Remove a Hash key using except

I have a Hash like this:

my_hash = {
"user_attributes" => {
     "email" => "[email protected]", 
     "person_attributes" => {
           "first_name" => "a_name", 
           "last_name" => "a_name"
      }
  }
}

I want to remove all the "person_attributes" content, so I used:

my_hash.except("person_attributes")

But that does not do anything. How can I remove a sub-hash key?

Upvotes: 1

Views: 436

Answers (1)

raviture
raviture

Reputation: 1059

You will have to use this to get the my_hash['user_attrbiutes'] except person_attributes:

2.1.0 :010 > my_hash['user_attributes'].except('person_attributes')
 => {"email"=>"[email protected]"} 

To get the output as {"user_attributes"=>{"email"=>"[email protected]"}} you can use:

 => {"user_attributes"=>{"email"=>"[email protected]", "person_attributes"=>{"first_name"=>"a_name", "last_name"=>"a_name"}}} 
2.1.0 :026 > my_hash['user_attributes'].delete('person_attributes')
 => {"first_name"=>"a_name", "last_name"=>"a_name"} 
2.1.0 :027 > my_hash
 => {"user_attributes"=>{"email"=>"[email protected]"}} 

Upvotes: 3

Related Questions