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?
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]
nil element. * Also, it can be written as a = b.any? ? b : c. * HOWEVER, it does fail if there are elements with value false.Do as below :
a = b.compact.empty? ? c : b
Array#compact will be helpful method in this case, I think.
compactfor arrays too.selectandreject, you can get arrays that are empty, or only contain valid values, making it easier to process at that point.