Ruby-on-rails 哈希删除除特定键之外的所有内容
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6619765/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Hash remove all except specific keys
提问by glarkou
I would like to remove every key from a hash except a given key.
我想从散列中删除除给定键之外的每个键。
For example:
例如:
{
"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"
}
]
}
I want to remove everything except "firstName" and/or "address"
我想删除除“名字”和/或“地址”之外的所有内容
Thanks
谢谢
采纳答案by Jake Dempsey
Some other options:
其他一些选择:
h.select {|k,v| ["age", "address"].include?(k) }
Or you could do this:
或者你可以这样做:
class Hash
def select_keys(*args)
select {|k,v| args.include?(k) }
end
end
So you can now just say:
所以你现在可以说:
h.select_keys("age", "address")
回答by Mario Uher
What about slice?
怎么样slice?
hash.slice('firstName', 'lastName')
# => { 'firstName' => 'John', 'lastName' => 'Smith' }
回答by Jim Deville
Hash#select does what you want:
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}
Edit (for comment):
编辑(评论):
assuming h is your hash above:
假设 h 是你上面的哈希:
h.select {|k,v| k == "age" || k == "address" }
回答by asiniy
If you use Rails, please consider ActiveSupport except()method: http://apidock.com/rails/Hash/except
如果你使用 Rails,请考虑 ActiveSupportexcept()方法: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 }
回答by starkovv
Inspired by Jake Dempsey's answer, this one should be faster for large hashes, as it only peaks explicit keys rather than iterating through the whole hash:
受到 Jake Dempsey's answer 的启发,对于大散列,这个应该更快,因为它只对显式键进行峰值处理,而不是遍历整个散列:
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
回答by ribamar
No Rails needed to get a very concise code:
无需 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
回答by ar31an
hash = { a: true, b: false, c: nil }
hash.extract!(:c) # => { c: nil }
hash # => { a: true, b: false }

