1
array1= [{},nil,[]]
array2=[{},23,45]

These are my input I used .nil? and .empty? function. The the both are gives false but the first one is nil

I need help with this this

1
  • nil? checks whether the receiver is nil, not if it contains it. Commented Jan 13, 2021 at 6:28

2 Answers 2

4

array.nil? checks if array is nil, not if it contains a nil value. Similarly, array.empty? checks if array contains no elements.

If you want to check if any element is nil, use any?.

array.any? { |element| element.nil? }

That can be shortened to array.any?(nil).

Sign up to request clarification or add additional context in comments.

4 Comments

Another (albeit less desirable) way: arr != arr.compact.
@CarySwoveland That's, uhh... why?
Why? Because it's there. OK, then how about arr.any?(NilClass)? Also, "shortened" may not be the right word.
@CarySwoveland a.group_by(&:nil?).key?(true) ;)
1

Actually you are mis-understanding the functionality of .nil? and .empty?. “.nil?” Will only return true for “nil” values i.e. “nil.nil? => true” but “[].nil? => false”.

Coming to “.empty?” if you see your variables “array1 and array2” both have some elements, it doesn’t matter if they have nil values, empty array or hashes, but what matters is both of them has 3 elements each. This will help you understanding the difference.

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.