ProgramingTip

해시의 키에 모든 키 집합이 존재 확인

bestdevel 2021. 1. 9. 16:26
반응형

해시의 키에 모든 키 집합이 존재 확인


더 나은 방법을 찾고 있습니다.

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]

그러나 나는 배열을 두 번 추가하는 것을 좋아하지 않는다.


%i[a b c d].all? {|s| hash.key? s}

@Mori의 방법이 가장 좋지만 다른 방법이 있습니다.

([:a, :b, :c, :d] - hash.keys).empty?

또는

hash.slice(:a, :b, :c, :d).size == 4

TIMTOWTDI의 정신으로 다른 방법이 있습니다. 당신은이 경우 require 'set'(성병 lib 디렉토리는) 당신은이 작업을 수행 할 수 있습니다.

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?

나는 제출 해결 방법을 좋아합니다.

subset = [:a, :b, :c, :d]
subset & hash.keys == subset

빠르고 명확합니다.


내 해결은 다음과 달라집니다.

( 에서 답변으로도 제공됨 )

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?("jack").inspect       # => nil
puts a.same_keys?({}).inspect           # => false

참조 URL : https://stackoverflow.com/questions/11552490/check-if-a-hashs-keys-include-all-of-a-set-of-keys

반응형