私はより良い方法を探しています
if hash.key? :a &&
hash.key? :b &&
hash.key? :c &&
hash.key? :d
できれば次のようなもの
hash.includes_keys? [ :a, :b, :c, :d ]
私が思いついた
hash.keys & [:a, :b, :c, :d] == [:a, :b, :c, :d]
しかし、配列を2回追加する必要はありません
私はより良い方法を探しています
if hash.key? :a &&
hash.key? :b &&
hash.key? :c &&
hash.key? :d
できれば次のようなもの
hash.includes_keys? [ :a, :b, :c, :d ]
私が思いついた
hash.keys & [:a, :b, :c, :d] == [:a, :b, :c, :d]
しかし、配列を2回追加する必要はありません
%i[a b c d].all? {|s| hash.key? s}
@Mori's way is best, but here's another way:
([:a, :b, :c, :d] - hash.keys).empty?
or
hash.slice(:a, :b, :c, :d).size == 4
TIMTOWTDI の精神から、別の方法があります。あなたがrequire 'set'
(標準ライブラリにある)場合、これを行うことができます:
Set[:a,:b,:c,:d].subset? hash.keys.to_set
次の方法で、不足しているキーのリストを取得できます。
expected_keys = [:a, :b, :c, :d]
missing_keys = expected_keys - hash.keys
不足しているキーがあるかどうかを確認したいだけの場合:
(expected_keys - hash.keys).empty?
これが私の解決策です:
class Hash
# doesn't check recursively
def same_keys?(compare)
return unless compare.class == Hash
self.size == compare.size && self.keys.all? { |s| compare.key?(s) }
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?("jack").inspect # => nil
puts a.same_keys?({}).inspect # => false