123456789_123456789_123456789_123456789_123456789_

Class: RuboCop::Cop::Style::ArrayIntersect

Relationships & Source Files
Super Chains via Extension / Inclusion / Inheritance
Class Chain:
Instance Chain:
Inherits: RuboCop::Cop::Base
Defined in: lib/rubocop/cop/style/array_intersect.rb

Overview

In Ruby 3.1, Array#intersect? has been added.

This cop identifies places where:

  • (array1 & array2).any?

  • (array1.intersection(array2)).any?

  • array1.any? { |elem| array2.member?(elem) }

  • (array1 & array2).count > 0

  • (array1 & array2).size > 0

can be replaced with array1.intersect?(array2).

array1.intersect?(array2) is faster and more readable.

In cases like the following, compatibility is not ensured, so it will not be detected when using block argument.

([1] & [1,2]).any? { |x| false }    # => false
[1].intersect?([1,2]) { |x| false } # => true
Note
Although Array#intersection can take zero or multiple arguments, only cases where exactly one argument is provided can be replaced with Array#intersect? and are handled by this cop.
Note
In the block form, include? is only detected when its receiver is an array literal, because include? is defined with different semantics on many non-array classes (e.g. String#include? checks for substrings). member? does not have this restriction.

Examples:

# bad
(array1 & array2).any?
(array1 & array2).empty?
(array1 & array2).none?

# bad
array1.intersection(array2).any?
array1.intersection(array2).empty?
array1.intersection(array2).none?

# bad
array1.any? { |elem| array2.member?(elem) }
array1.none? { |elem| [1, 2].include?(elem) }

# good
array1.intersect?(array2)
!array1.intersect?(array2)

# bad
(array1 & array2).count > 0
(array1 & array2).count.positive?
(array1 & array2).count != 0

(array1 & array2).count == 0
(array1 & array2).count.zero?

# good
array1.intersect?(array2)

!array1.intersect?(array2)

AllCops:ActiveSupportExtensionsEnabled: false (default)

# good
(array1 & array2).present?
(array1 & array2).blank?

AllCops:ActiveSupportExtensionsEnabled: true

# bad
(array1 & array2).present?
(array1 & array2).blank?

# good
array1.intersect?(array2)
!array1.intersect?(array2)

Cop Safety Information:

  • This cop cannot guarantee that array1 and array2 are actually arrays while method intersect? is for arrays only.

Constant Summary

::RuboCop::Cop::Base - Inherited

EMPTY_OFFENSES, RESTRICT_ON_SEND

Class Attribute Summary

::RuboCop::Cop::AutoCorrector - Extended

::RuboCop::Cop::Base - Inherited

.gem_requirements, .lint?,
.support_autocorrect?

Returns if class supports autocorrect.

.support_multiple_source?

Override if your cop should be called repeatedly for multiple investigations Between calls to on_new_investigation and on_investigation_end, the result of processed_source will remain constant.

Class Method Summary

::RuboCop::Cop::TargetRubyVersion - Extended

::RuboCop::Cop::Base - Inherited

.autocorrect_incompatible_with

List of cops that should not try to autocorrect at the same time as this cop.

.badge

Naming.

.callbacks_needed, .cop_name, .department,
.documentation_url

Returns a url to view this cops documentation online.

.exclude_from_registry

Call for abstract Cop classes.

.inherited,
.joining_forces

Override and return the Force class(es) you need to join.

.match?

Returns true if the cop name or the cop namespace matches any of the given names.

.new,
.requires_gem

Register a version requirement for the given gem name.

.restrict_on_send

::RuboCop::ExcludeLimit - Extended

exclude_limit

Sets up a configuration option to have an exclude limit tracked.

transform

Instance Attribute Summary

Instance Method Summary

::RuboCop::Cop::Base - Inherited

#add_global_offense

Adds an offense that has no particular location.

#add_offense

Adds an offense on the specified range (or node with an expression) Unless that offense is disabled for this range, a corrector will be yielded to provide the cop the opportunity to autocorrect the offense.

#begin_investigation

Called before any investigation.

#callbacks_needed,
#cop_config

Configuration Helpers.

#cop_name, #excluded_file?,
#external_dependency_checksum

This method should be overridden when a cop’s behavior depends on state that lives outside of these locations:

#inspect,
#message

Gets called if no message is specified when calling add_offense or add_global_offense Cops are discouraged to override this; instead pass your message directly.

#name

Alias for Base#cop_name.

#offenses,
#on_investigation_end

Called after all on_…​

#on_new_investigation

Called before all on_…​

#on_other_file

Called instead of all on_…​

#parse

There should be very limited reasons for a Cop to do it’s own parsing.

#parser_engine,
#ready

Called between investigations.

#relevant_file?,
#target_gem_version

Returns a gems locked versions (i.e.

#target_rails_version, #target_ruby_version, #annotate, #apply_correction, #attempt_correction,
#callback_argument

Reserved for Cop::Cop.

#complete_investigation

Called to complete an investigation.

#correct, #current_corrector,
#current_offense_locations

Reserved for Commissioner:

#current_offenses, #currently_disabled_lines, #custom_severity, #default_severity, #disable_uncorrectable, #enabled_line?, #file_name_matches_any?, #find_message, #find_severity, #matches_absolute_include_pattern?, #range_for_original, #range_from_node_or_range,
#reset_investigation

Actually private methods.

#use_corrector

::RuboCop::Cop::AutocorrectLogic - Included

::RuboCop::Cop::IgnoredNode - Included

Constructor Details

This class inherits a constructor from RuboCop::Cop::Base

Instance Method Details

#any_none_block_intersection(node)

[ GitHub ]

  
# File 'lib/rubocop/cop/style/array_intersect.rb', line 124

def_node_matcher :any_none_block_intersection, <<~PATTERN
  {
    (block
      (call $_receiver ${:any? :none?})
      (args (arg _key))
      (send $!nil? ${:member? :include?} (lvar _key))
    )
    (numblock
      (call $_receiver ${:any? :none?}) 1
      (send $!nil? ${:member? :include?} (lvar :_1))
    )
    (itblock
      (call $_receiver ${:any? :none?}) :it
      (send $!nil? ${:member? :include?} (lvar :it))
    )
  }
PATTERN

#bad_intersection?(node) ⇒ Boolean (private)

[ GitHub ]

  
# File 'lib/rubocop/cop/style/array_intersect.rb', line 184

def bad_intersection?(node)
  bad_intersection_check?(node, bad_intersection_predicates) ||
    intersection_size_check?(node)
end

#bad_intersection_check?(node, predicates)

[ GitHub ]

  
# File 'lib/rubocop/cop/style/array_intersect.rb', line 99

def_node_matcher :bad_intersection_check?, <<~PATTERN
  $(call
    {
      (begin (send $_ :& $_))
      (call $!nil? :intersection $_)
    }
    $%1
  )
PATTERN

#bad_intersection_predicates (private)

[ GitHub ]

  
# File 'lib/rubocop/cop/style/array_intersect.rb', line 189

def bad_intersection_predicates
  if active_support_extensions_enabled?
    ACTIVE_SUPPORT_PREDICATES
  else
    PREDICATES
  end
end

#intersection_size_check?(node, predicates)

[ GitHub ]

  
# File 'lib/rubocop/cop/style/array_intersect.rb', line 110

def_node_matcher :intersection_size_check?, <<~PATTERN
  (call
    $(call
      {
        (begin (send $_ :& $_))
        (call $!nil? :intersection $_)
      }
      %ARRAY_SIZE_METHODS
    )
    {$:> (int 0) | $:positive? | $:!= (int 0) | $:== (int 0) | $:zero?}
  )
PATTERN

#on_block(node) Also known as: #on_numblock, #on_itblock

[ GitHub ]

  
# File 'lib/rubocop/cop/style/array_intersect.rb', line 163

def on_block(node)
  return unless (captures = any_none_block_intersection(node))

  receiver, method_name, argument, block_method = captures

  # `include?` is defined with different semantics on many non-array classes
  # (e.g. `String#include?` checks for substrings), so it is only a reliable
  # signal of an intersection check when the receiver is an array literal.
  return if block_method == :include? && !argument.array_type?

  dot = node.send_node.loc.dot.source
  bang = method_name == :any? ? '' : '!'
  replacement = "#{bang}#{receiver.source}#{dot}intersect?(#{argument.source})"

  register_offense(node, replacement)
end

#on_csend(node)

Alias for #on_send.

[ GitHub ]

  
# File 'lib/rubocop/cop/style/array_intersect.rb', line 161

alias on_csend on_send

#on_itblock(node)

Alias for #on_block.

[ GitHub ]

  
# File 'lib/rubocop/cop/style/array_intersect.rb', line 180

alias on_itblock on_block

#on_numblock(node)

Alias for #on_block.

[ GitHub ]

  
# File 'lib/rubocop/cop/style/array_intersect.rb', line 179

alias on_numblock on_block

#on_send(node) Also known as: #on_csend

[ GitHub ]

  
# File 'lib/rubocop/cop/style/array_intersect.rb', line 147

def on_send(node)
  return if node.block_literal?
  return unless (dot_node, receiver, argument, method_name = bad_intersection?(node))

  dot = dot_node.loc.dot.source
  bang = straight?(method_name) ? '' : '!'
  # `a&.intersection(b)&.none?` returns `nil` when `a` is `nil`, but the negated
  # rewrite `!a&.intersect?(b)` returns `true` there, flipping the result.
  return if bang == '!' && dot == '&.'

  replacement = "#{bang}#{receiver.source}#{dot}intersect?(#{argument.source})"

  register_offense(node, replacement)
end

#register_offense(node, replacement) (private)

[ GitHub ]

  
# File 'lib/rubocop/cop/style/array_intersect.rb', line 201

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

#straight?(method_name) ⇒ Boolean (private)

[ GitHub ]

  
# File 'lib/rubocop/cop/style/array_intersect.rb', line 197

def straight?(method_name)
  STRAIGHT_METHODS.include?(method_name.to_sym)
end