Intersection of non-empty arrays

I have three arrays that I want to traverse, but I want to ignore those that are empty.

This code looks 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 
+4
source share
2 answers

What about

 abc = [a,b,c].reject(&:empty?).reduce(:&) 

The first part, [a,b,c] puts your arrays into an array. The second bit with reject runs empty? for each element and rejects it if the result is true, returning an array of arrays where empty arrays are deleted. In the last part of reduce , the equivalent of your a & b & c is executed, but since we discarded all empty arrays in the previous step, you will not get an empty result.

+11
source

A bit late to the party ...

 a = [1,3,4,5] b = [] c = [2,3,5,6] t = a | b | c # => [1, 3, 4, 5, 2, 6] [a,b,c].map {|e| e.empty? ? t : e}.reduce(:&) # => [3, 5] 
0
source

Source: https://habr.com/ru/post/1445240/


All Articles