123456789_123456789_123456789_123456789_123456789_

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

Relationships & Source Files
Super Chains via Extension / Inclusion / Inheritance
Class Chain:
self, AutoCorrector, Base
Instance Chain:
self, Base
Inherits: Base
  • Object
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

Cop Safety Information:

  • This cop is unsafe because Range#include? (or Range#member?) and Range#cover? are not equivalent behavior. Example of a case where Range#cover? may not provide the desired result:

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

Constant Summary

Instance Method Summary

Instance Method Details

#on_csend(node)

Alias for #on_send.

[ GitHub ]

  
# File 'lib/rubocop/cop/performance/range_include.rb', line 53

alias on_csend on_send

#on_send(node) Also known as: #on_csend

[ GitHub ]

  
# 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