Check if a hash's keys include all of a set of keys

后端 未结 6 594
天命终不由人
天命终不由人 2020-12-24 10:38

I\'m looking for a better way to do

if hash.key? :a &&
   hash.key? :b &&
   hash.key? :c &&
   hash.key? :d

prefer

6条回答
  •  -上瘾入骨i
    2020-12-24 11:17

    Here is my solution:

    (also given as answer at)

    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
    

提交回复
热议问题