开发者

rails - building a line of code from a foreach loop

I am trying to create a intersection statement usin开发者_运维百科g 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


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


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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜