开发者

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

开发者 https://www.devze.com 2023-01-27 09:33 出处:网络
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开发者_JAVA技巧 least one element in the hash is nil.You can use all?

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开发者_JAVA技巧 least one element in the hash is nil.


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


Enumerable#all? method does exactly what you need.


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


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
0

精彩评论

暂无评论...
验证码 换一张
取 消