Ruby 3.1 introduced the Array#intersect?
method which returns true if two arrays have at least one common element, otherwise returns false.
fruits_list_1 = ['apple', 'banana', 'cherry']
fruits_list_2 = ['orange', 'banana', 'grape']
fruits_list_3 = ['kiwi', 'peach', 'mango']
fruits_list_1.intersect?(fruits_list_2)
=> true
fruits_list_1.intersect?(fruits_list_3)
=> false
Before
To check if two ActiveRecord relation objects have any common elements, we had to chain the intersection
method with any?
or empty?
methods.
products1 = Product.where(id: [1, 2, 3])
=> [#<Product id: 1, name:...>, #<Product id: 2, name:...>, #<Product id: 3, name:...>]
products2 = Product.where(id: [2, 4, 5])
=> [#<Product id: 2, name:...>, #<Product id: 4, name:...>, #<Product id: 5, name:...>]
(products1 & products2).any?
=> true
(products1 & products2).empty?
=> false
But the ActiveRecord::Relation
did not have built-in support for the Array#intersect
method.
products1.intersect?(products2)
NoMethodError: undefined method `intersect?' for #<ActiveRecord::Relation....
After
Rails 7.1 added the Array#intersect? method to ActiveRecord::Relation.
With this intersect?
method, we can check if two ActiveRecord relation objects have any common elements or not.
products1.intersect?(products2)
=> true
Refer