I have three arrays I want to intersect, but I want to ignore the ones that are empty.
This code seems too verbose. Is there a more efficient approach?
if a.empty? && b.empty?
abc = c
elsif a.empty? && c.empty?
abc = b
elsif b.empty? && c.empty?
abc = a
elsif a.empty?
abc = b & c
elsif b.empty?
abc = a & c
elsif c.empty?
abc = a & b
else
abc = a & b & c
end
How about
abc = [a,b,c].reject(&:empty?).reduce(:&)
The first part, [a,b,c]
puts your arrays in an array. The second bit with reject
runs empty?
on every element and rejects it if the result is true, returning an array of arrays where the empty arrays are removed. The last part, reduce
runs the equivalent of your a & b & c
but since we discarded all empty arrays in the previous step, you don't end up with an empty result.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With