Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

ruby

hash

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.

like image 821
krn Avatar asked Nov 27 '10 17:11

krn


People also ask

How can you tell if a key is present in a hash?

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.

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

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.

Is Hash in Ruby ordered?

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.


2 Answers

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?}
like image 134
sepp2k Avatar answered Sep 20 '22 10:09

sepp2k


Another way:

!hash.values.include? nil
like image 44
Mark Thomas Avatar answered Sep 20 '22 10:09

Mark Thomas