4

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
2
  • those s's are c's? are they arrays? Commented Nov 10, 2012 at 18:10
  • I assumed so and edited. I also assumed that a, b and c are arrays that may or may not me empty. Commented Nov 10, 2012 at 18:14

2 Answers 2

11

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.

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

Comments

0

A little 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]

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.