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

时间:2011-07-08 03:47:04

标签: ruby-on-rails ruby ruby-on-rails-3

除了给定的密钥之外,我想从哈希中删除每个密钥。

例如:

{
 "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"
     }
 ]
}

我想删除除“firstName”和/或“address”

之外的所有内容

由于

7 个答案:

答案 0 :(得分:242)

slice怎么样?

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

答案 1 :(得分:46)

其他一些选择:

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")

答案 2 :(得分:6)

哈希#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" }

答案 3 :(得分:1)

受到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

答案 4 :(得分:1)

如果您使用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 }

答案 5 :(得分:0)

没有Rails需要获得非常简洁的代码:

keys = [ "firstName" , "address" ]
# keys = hash.keys - (hash.keys - keys) # uncomment if needed to preserve hash order
keys.zip(hash.values_at *keys).to_h

答案 6 :(得分:0)

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