jmasterx
jmasterx

Reputation: 54123

Check if keys in a hashmap are all in an array

Say I have the array a = ["a","b"] And the hashmap {"hello" => "world", "a" => "d"}

That would return false because "hello" is not in the array 'a'.

The hashmap: {"a" => "hello", "a" => "world"} is fine.

Is there a way to do this without manually doing all the work? eg: find if the hashmap keys are a subset of the array?

Upvotes: 1

Views: 69

Answers (3)

mr. Holiday
mr. Holiday

Reputation: 1800

are you looking for this

a = ["a","b"]
b = {"hello" => "world", "a" => "d"}

(a-b.keys).empty?

Upvotes: 0

Stanislav Mekhonoshin
Stanislav Mekhonoshin

Reputation: 4386

Try something like this:

keys = hashmap.keys
(keys - a).empty?

Is result 'keys - a' is empty - it means that all keys are in array

Upvotes: 0

Arup Rakshit
Arup Rakshit

Reputation: 118271

This will work:

(hash.keys - a).empty?
# if returns true means all keys present in array.
# if returns false means all keys are not present in array.

Upvotes: 3

Related Questions