ruby 散列删除除特定键以外的所有键

9bfwbjaz  于 2023-06-29  发布在  Ruby
关注(0)|答案(7)|浏览(105)

我想从散列中删除除给定键之外的所有键。
例如:

{
 "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”之外的所有内容。

oewdyzsn

oewdyzsn1#

Hash#slice怎么样?

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

自2.5起提供Ruby

bxjv4tth

bxjv4tth2#

一些其他选项:

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

ajsxfq5m3#

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

gpnt7bae4#

Hash#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是上面的hash:

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

yhived7q5#

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

odopli946#

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

yrefmtwq7#

没有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

相关问题