class RuboCop::Cop::Style::ArrayIntersect
!array1.intersect?(array2)
array1.intersect?(array2)
# good
(array1 & array2).blank?
(array1 & array2).present?
# bad
@example AllCops:ActiveSupportExtensionsEnabled: true
(array1 & array2).blank?
(array1 & array2).present?
# good
@example AllCops:ActiveSupportExtensionsEnabled: false (default)
!array1.intersect?(array2)
array1.intersect?(array2)
# good
array1.none? { |elem| array2.member?(elem) }
array1.any? { |elem| array2.member?(elem) }
# bad
array1.intersection(array2).none?
array1.intersection(array2).empty?
array1.intersection(array2).any?
# bad
(array1 & array2).none?
(array1 & array2).empty?
(array1 & array2).any?
# bad
@example
actually arrays while method ‘intersect?` is for arrays only.
This cop cannot guarantee that `array1` and `array2` are
@safety
`Array#intersect?` and are handled by this cop.
only cases where exactly one argument is provided can be replaced with
NOTE: Although `Array#intersection` can take zero or multiple arguments,<br><br>—-<br>.intersect?() { |x| false } # => true<br>( & [1,2]).any? { |x| false } # => false
—-
[source,ruby]
so it will not be detected when using block argument.
In cases like the following, compatibility is not ensured,
`array1.intersect?(array2)` is faster and more readable.
can be replaced with `array1.intersect?(array2)`.
* `array1.any? { |elem| array2.member?(elem) }`
* `(array1.intersection(array2)).any?`
* `(array1 & array2).any?`
This cop identifies places where:
In Ruby 3.1, `Array#intersect?` has been added.
def bad_intersection?(node)
def bad_intersection?(node) predicates = if active_support_extensions_enabled? ACTIVE_SUPPORT_PREDICATES else PREDICATES end bad_intersection_check?(node, predicates) end
def on_block(node)
def on_block(node) return unless (receiver, method_name, argument = any_none_block_intersection(node)) dot = node.send_node.loc.dot.source bang = method_name == :any? ? '' : '!' replacement = "#{bang}#{receiver.source}#{dot}intersect?(#{argument.source})" register_offense(node, replacement) end
def on_send(node)
def on_send(node) return if node.block_literal? return unless (receiver, argument, method_name = bad_intersection?(node)) dot = node.loc.dot.source bang = straight?(method_name) ? '' : '!' replacement = "#{bang}#{receiver.source}#{dot}intersect?(#{argument.source})" register_offense(node, replacement) end
def register_offense(node, replacement)
def register_offense(node, replacement) message = format(MSG, replacement: replacement, existing: node.source) add_offense(node, message: message) do |corrector| corrector.replace(node, replacement) end end
def straight?(method_name)
def straight?(method_name) STRAIGHT_METHODS.include?(method_name.to_sym) end