Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Intersecting non-empty arrays

Tags:

ruby

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
like image 668
keypulsations Avatar asked Dec 21 '22 13:12

keypulsations


1 Answers

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.

like image 139
edgerunner Avatar answered Dec 29 '22 16:12

edgerunner