learnvst
learnvst

Reputation: 16195

Finding keys in a hash that do not exist in an array

In Ruby, one can find which keys exist in both a hash and an array using the following

(hash.keys & array_of_keys)

What operator do I need to use in order to find keys in the hash that do not exist in the array?

Upvotes: 0

Views: 41

Answers (2)

Andrea Salicetti
Andrea Salicetti

Reputation: 2483

Simply hash.keys - array_of_keys.

hash = {a: 'a', b: 'b', c: 'c'}
array_of_keys = [:a, :c]

hash.keys - array_of_keys
# => [:b]

Upvotes: 4

falsetru
falsetru

Reputation: 369274

Use Array#-

h = {a: 1, b: 2}
h.keys - [:c, :b]
# => [:a]

Upvotes: 2

Related Questions