Пересечение Ruby Array: методы и примеры

Чтобы найти пересечение нескольких массивов в Ruby, вы можете использовать различные методы и приемы. Вот несколько примеров:

  1. Использование оператора &:

    arr1 = [1, 2, 3]
    arr2 = [2, 3, 4]
    arr3 = [3, 4, 5]
    
    intersection = arr1 & arr2 & arr3
    puts intersection.inspect
    # Output: [3]
  2. Использование метода intersection:

    arr1 = [1, 2, 3]
    arr2 = [2, 3, 4]
    arr3 = [3, 4, 5]
    
    intersection = arr1.intersection(arr2, arr3)
    puts intersection.inspect
    # Output: [3]
  3. Использование метода reduce:

    arrays = [[1, 2, 3], [2, 3, 4], [3, 4, 5]]
    
    intersection = arrays.reduce(:&)
    puts intersection.inspect
    # Output: [3]
  4. Использование метода select:

    arrays = [[1, 2, 3], [2, 3, 4], [3, 4, 5]]
    
    intersection = arrays.first.select { |element| arrays.all? { |array| array.include?(element) } }
    puts intersection.inspect
    # Output: [3]
  5. Использование класса Set:

    require 'set'
    
    set1 = Set.new([1, 2, 3])
    set2 = Set.new([2, 3, 4])
    set3 = Set.new([3, 4, 5])
    
    intersection = set1.intersection(set2, set3).to_a
    puts intersection.inspect
    # Output: [3]