Class: RuboCop::Cop::Performance::RangeInclude

Inherits:
Base
  • Object
show all
Extended by:
AutoCorrector
Defined in:
lib/rubocop/cop/performance/range_include.rb

Overview

Identifies uses of ‘Range#include?` and `Range#member?`, which iterates over each item in a `Range` to see if a specified item is there. In contrast, `Range#cover?` simply compares the target item with the beginning and end points of the `Range`. In a great majority of cases, this is what is wanted.

Examples:

# bad
('a'..'z').include?('b') # => true
('a'..'z').member?('b')  # => true

# good
('a'..'z').cover?('b') # => true

Constant Summary collapse

MSG =
'Use `Range#cover?` instead of `Range#%<bad_method>s`.'
RESTRICT_ON_SEND =
%i[include? member?].freeze

Instance Method Summary collapse

Instance Method Details

#on_send(node) ⇒ Object Also known as: on_csend



44
45
46
47
48
49
50
51
52
# File 'lib/rubocop/cop/performance/range_include.rb', line 44

def on_send(node)
  range_include(node) do |bad_method|
    message = format(MSG, bad_method: bad_method)

    add_offense(node.loc.selector, message: message) do |corrector|
      corrector.replace(node.loc.selector, 'cover?')
    end
  end
end