哈希删除除特定的键以外的所有

我想从一个哈希除了给定的密钥除去每个密钥。

例如:

{ "firstName": "John", "lastName": "Smith", "age": 25, "address": { "streetAddress": "21 2nd Street", "city": "New York", "state": "NY", "postalCode": "10021" }, "phoneNumber": [ { "type": "home", "number": "212 555-1234" }, { "type": "fax", "number": "646 555-4567" } ] } 

我想删除除“名字”和/或“地址”之外的所有内容

谢谢

其他一些选项:

 h.select {|k,v| ["age", "address"].include?(k) } 

或者你可以这样做:

 class Hash def select_keys(*args) select {|k,v| args.include?(k) } end end 

所以你现在可以说:

 h.select_keys("age", "address") 

那么slice呢?

 hash.slice('firstName', 'lastName') # => { 'firstName' => 'John', 'lastName' => 'Smith' } 

哈希#select做你想要的:

  h = { "a" => 100, "b" => 200, "c" => 300 } h.select {|k,v| k > "a"} #=> {"b" => 200, "c" => 300} h.select {|k,v| v < 200} #=> {"a" => 100} 

编辑(评论):

假设h是你的散列之上:

 h.select {|k,v| k == "age" || k == "address" } 

如果您使用Rails,请考虑ActiveSupport except()方法: http ://apidock.com/rails/Hash/except

 hash = { a: true, b: false, c: nil} hash.except!(:c) # => { a: true, b: false} hash # => { a: true, b: false } 

受Jake Dempsey的回答的启发,对于大哈希来说,这个应该是更快的,因为它只能达到明确的密钥而不是遍历整个哈希:

 class Hash def select_keys(*args) filtered_hash = {} args.each do |arg| filtered_hash[arg] = self[arg] if self.has_key?(arg) end return filtered_hash end end