0
array = [[1555,100],[nil,95],[1774,nil],[1889,255]]

What would be the best way to remove the 2nd and 3rd elements from array since they have NULL fields?

Expected output :

array = [[1555,100],[1889,255]]
2
  • Can you paste the expected output for above example? Commented Oct 26, 2021 at 6:05
  • @Ragnar921 : You mean nil, not NULL. Ruby does not have a NULL. Commented Oct 26, 2021 at 6:32

3 Answers 3

5
arr = [[1555,100],[nil,95],[1774,nil],[1889,255]]
arr.reject { |a,b| (a && b).nil? }
  #=> [[1555, 100], [1889, 255]]
Sign up to request clarification or add additional context in comments.

Comments

4

And yet another option:

array.reject { |a| a.any?(&:nil?) }

It is very similar to Cary Swoveland's answer, but will work with arrays of any length and will remove [false, nil] as well.

Comments

0

Use .compact to remove nil elements from array of arrays

array.map(&:compact)

# array = [[1555,100], [95], [1774], [1889, 255]]

Edit

Use .reject! to remove sub arrays containing nil elements.

array.reject! { |e| e.any? nil }

# array = [[1555,100], [1889,255]]

2 Comments

I want the whole array element gone if it includes a NULL
I have edit the answer.

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.