ruby 检查散列的键是否包含所有一组键
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11552490/
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
Check if a hash's keys include all of a set of keys
提问by Greg Guida
I'm looking for a better way to do
我正在寻找更好的方法
if hash.key? :a &&
hash.key? :b &&
hash.key? :c &&
hash.key? :d
preferably something like
最好是这样的
hash.includes_keys? [ :a, :b, :c, :d ]
I came up with
我想出了
hash.keys & [:a, :b, :c, :d] == [:a, :b, :c, :d]
but I dont like having to add the array twice though
但我不喜欢不得不将数组添加两次
回答by Mori
%i[a b c d].all? {|s| hash.key? s}
回答by John Douthat
@Mori's way is best, but here's another way:
@Mori 的方式是最好的,但这是另一种方式:
([:a, :b, :c, :d] - hash.keys).empty?
or
或者
hash.slice(:a, :b, :c, :d).size == 4
回答by Mark Thomas
Just in the spirit of TIMTOWTDI, here's another way. If you require 'set'(in the std lib) then you can do this:
只是本着 TIMTOWTDI 的精神,这是另一种方式。如果你require 'set'(在标准库中)那么你可以这样做:
Set[:a,:b,:c,:d].subset? hash.keys.to_set
回答by Chris Hanson
You can get a list of missing keys this way:
您可以通过以下方式获取缺失键的列表:
expected_keys = [:a, :b, :c, :d]
missing_keys = expected_keys - hash.keys
If you just want to see if there are any missing keys:
如果您只想查看是否有任何丢失的键:
(expected_keys - hash.keys).empty?
回答by swilgosz
I like this way to solve this:
我喜欢这种方式来解决这个问题:
subset = [:a, :b, :c, :d]
subset & hash.keys == subset
It is fast and clear.
它快速而清晰。
回答by Alphons
Here is my solution:
这是我的解决方案:
(也作为答案给出)
class Hash
# doesn't check recursively
def same_keys?(compare)
if compare.class == Hash
if self.size == compare.size
self.keys.all? {|s| compare.key?(s)}
else
return false
end
else
nil
end
end
end
a = c = { a: nil, b: "whatever1", c: 1.14, d: false }
b = { a: "foo", b: "whatever2", c: 2.14, "d": false }
d = { a: "bar", b: "whatever3", c: 3.14, }
puts a.same_keys?(b) # => true
puts a.same_keys?(c) # => true
puts a.same_keys?(d) # => false
puts a.same_keys?(false).inspect # => nil
puts a.same_keys?("Hyman").inspect # => nil
puts a.same_keys?({}).inspect # => false

