class RuboCop::Cop::Performance::RangeInclude

This cop 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.

This cop is `Safe: false` by default because `Range#include?` (or `Range#member?`) and `Range#cover?` are not equivalent behaviour.

@example

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

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

# Example of a case where `Range#cover?` may not provide
# the desired result:

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

Constants

MSG
RESTRICT_ON_SEND

Public Instance Methods

on_send(node) click to toggle source
# File lib/rubocop/cop/performance/range_include.rb, line 42
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