1

I have a variable:

my_arr

which may be nil or an array. I would like to verify if it contains at least one element. It can be accomplished by:

my_arr && !my_arr.empty?

but I want to write it simpler. I tried:

!my_arr.empty?

but it fails if my_arr is nil. Is there a simple way?

3
  • There’s my_arr&.empty? == false, which is… not better. Also (my_arr || []).empty?, also not better. Just stick with what you have. Commented Nov 9, 2017 at 22:49
  • could array possibly contain nil and/or false values? Commented Nov 9, 2017 at 22:51
  • Just make sure that my_arr is always an array. Why should something that is supposed to be an array actually be nil? Commented Nov 9, 2017 at 22:54

2 Answers 2

3

This would work:

my_arr.to_a.empty?

Because:

nil.to_a #=> []

An array instance on the other hand just returns itself.

The same "trick" works for other classes:

nil.to_h.empty? #=> true
nil.to_s.empty? #=> true
nil.to_i.zero?  #=> true
Sign up to request clarification or add additional context in comments.

Comments

1

You can use safe access operator and any? method in case your array can't possibly contain nil and false values:

my_arr&.any?

In case it can, you could use any?(&:to_s), which seems neither native nor more elegant than your original solution.

Generally it is a better idea to be sure that it is always going to be an array, or at least something with the same duck type support.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.