0

I can assign a variable, such that if b is nil, c will be assigned to a.

a = b || c 

What's a good way to do the same for an array that has only nil elements?

This is my way:

a = b unless b.to_a.empty? 
a = c unless a.to_a.empty?
2
  • You may be interest in compact for arrays too. Commented Apr 2, 2014 at 18:11
  • 1
    Having an array containing only nil elements is suspicious. You might want to look at the code generating such an array. Usually, by a little bit of refactoring and use of select and reject, you can get arrays that are empty, or only contain valid values, making it easier to process at that point. Commented Apr 2, 2014 at 19:06

3 Answers 3

4

a = b.all?(&:nil?) ? c : b

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

3 Comments

Arup - From the OP: "What's a good way to do the same for an array that has only nil elements?"
How is my answer incorrect? I gave the OP exactly what he asked for.
How about a = (b+c).compact?
3

I'd suggest using any?:

b = [nil, nil]
c = [1, 2, 3]

b.any? #=> false
c.any? #=> true

a = [b, c].detect(&:any?)
a #=> [1, 2, 3]

1 Comment

This should be the most performant of the three solutions, as it stops as soon as it finds a non-nil element. * Also, it can be written as a = b.any? ? b : c. * HOWEVER, it does fail if there are elements with value false.
2

Do as below :

a = b.compact.empty? ? c : b

Array#compact will be helpful method in this case, I think.

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.