Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

ruby

I'm looking for a better way to do

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

preferably something like

hash.includes_keys? [ :a, :b, :c, :d ]  

I came up with

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

but I dont like having to add the array twice though

like image 842
Greg Guida Avatar asked Jul 19 '12 00:07

Greg Guida


People also ask

How do you get the key of a hash in Ruby?

Ruby | Hash key() functionHash#key() is a Hash class method which gives the key value corresponding to the value. If value doesn't exist then return nil.


1 Answers

%i[a b c d].all? {|s| hash.key? s} 
like image 133
Mori Avatar answered Oct 14 '22 11:10

Mori