使用except除去哈希键

时间:2014-07-01 14:32:24

标签: ruby-on-rails ruby

我有这样的哈希:

my_hash = {
"user_attributes" => {
     "email" => "email@email.com", 
     "person_attributes" => {
           "first_name" => "a_name", 
           "last_name" => "a_name"
      }
  }
}

我想删除所有"person_attributes"内容,因此我使用了:

my_hash.except("person_attributes")

但这没有任何作用。如何删除子哈希键?

1 个答案:

答案 0 :(得分:3)

您必须使用它来获取my_hash['user_attrbiutes'] except person_attributes

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

要将输出设为{"user_attributes"=>{"email"=>"email@email.com"}},您可以使用:

 => {"user_attributes"=>{"email"=>"email@email.com", "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@email.com"}}