Reputation: 6815
What is the best way to check if all the objects in the Ruby hash are defined (not nil)?
The statement should return false if at least one element in the hash is nil.
Upvotes: 15
Views: 13582
Reputation: 1
hash = { foo: nil, bar: nil, baz: nil }
hash.values.all?(nil) # true
!hash.values.all?(nil) # false
hash = { foo: 0, bar: nil, baz: nil }
hash.values.all?(nil) # false
!hash.values.all?(nil) # true
Upvotes: 0
Reputation: 81520
An element (value) that is nil
is defined. It's defined as the nil
object.
If you're wanting to check if there's any keys missing, then do the following:
hash = {:key1 => nil, :key2 => 42, :key3 => false}
keys = [:key1, :key2, :key3]
all_defined = keys.all?{|key| hash.has_key?(key)} # Returns true
Upvotes: 0
Reputation: 370172
You can use all?
to check whether a given predicate is true for all elements in an enumerable. So:
hash.values.all? {|x| !x.nil?}
Or
hash.all? {|k,v| !v.nil?}
If you also want to check, all the keys are non-nil as well, you can amend that to:
hash.all? {|k,v| !v.nil? && !k.nil?}
Upvotes: 46