views:

18

answers:

3

Hey,

I am trying to create a intersection statement using a foreach loop for example

cand[0][1,2,5]
cand[1][2,5,6]
@result = cand[0] & cand[1]

with a for each

  intersec = Array.new
  cand.each do |c|
    intersec = intersec & c
  end
  @result = intersec

I get an empty array

Thanks

Alex

A: 

Aren't you creating intersec as a blank array? And then trying to take the intersection of a blank array and some other existing array = blank array?

Not quite sure what you're trying to do here.

a.feng
A: 

I'm not entirely sure what result you are trying to get, but here's one thing I noticed. Try initializing your intersec array to the first value of cand. That way you aren't trying to find the non-existent intersection of an empty array and an element of cand.

bta
+1  A: 

I think you are trying to do something like

cand[0] & cand[1] & cand[2]

you can do this using

intersection = cand.reduce(:&)

Let me know if it works

Josh Crowder
Thanks that worked!
Alex