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

后端 未结 6 604
天命终不由人
天命终不由人 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条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-12-24 11:20

    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?
    

提交回复
热议问题