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.
We can check if a particular hash contains a particular key by using the method has_key?(key) . It returns true or false depending on whether the key exists in the hash or not.
hash.fetch(key) { | key | block } Returns a value from hash for the given key. If the key can't be found, and there are no other arguments, it raises an IndexError exception; if default is given, it is returned; if the optional block is specified, its result is returned.
We found a post on the Ruby mailing list from a couple of years ago which pointed out that from Ruby 1.9 the order is in fact maintained. Hashes are inherently unordered. Hashes provide amortized O(1) insertion and retrieval of elements by key, and that's it. If you need an ordered set of pairs, use an array of arrays.
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?}
Another way:
!hash.values.include? nil
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With