rails - Finding intersections between multiple arrays

后端 未结 3 2058
时光说笑
时光说笑 2021-01-30 12:19

I am trying to find the intersection values between multiple arrays.

for example

code1 = [1,2,3]
code2 = [2,3,4]
code3 = [0,2,6]

So the

相关标签:
3条回答
  • 2021-01-30 12:49

    Use the & method of Array which is for set intersection.

    For example:

    > [1,2,3] & [2,3,4] & [0,2,6]
    => [2]
    
    0 讨论(0)
  • 2021-01-30 12:55

    If you want a simpler way to do this with an array of arrays of unknown length, you can use inject.

    > arrays = [code1,code2,code3]
    > arrays.inject(:&)                   # Ruby 1.9 shorthand
    => [2]
    > arrays.inject{|codes,x| codes & x } # Full syntax works with 1.8 and 1.9
    => [2]
    
    0 讨论(0)
  • 2021-01-30 13:11

    Array#intersection (Ruby 2.7+)

    Ruby 2.7 introduced Array#intersection method to match the more succinct Array#&.

    So, now, [1, 2, 3] & [2, 3, 4] & [0, 2, 6] can be rewritten in a more verbose way, e.g.

    [1, 2, 3].intersection([2, 3, 4]).intersection([0, 2, 6])
    # => [2]
    
    [1, 2, 3].intersection([2, 3, 4], [0, 2, 6])
    # => [2]
    
    0 讨论(0)
提交回复
热议问题