krn
krn

Reputation: 6815

How do I confirm all elements in a hash are defined?

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

Answers (5)

Giulia Cajati
Giulia Cajati

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

Mark Thomas
Mark Thomas

Reputation: 37517

Another way:

!hash.values.include? nil

Upvotes: 12

Andrew Grimm
Andrew Grimm

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

Victor Deryagin
Victor Deryagin

Reputation: 12225

Enumerable#all? method does exactly what you need.

Upvotes: 2

sepp2k
sepp2k

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

Related Questions