Sha256: d290b9fdf834c98f3c08f21aa131756de0e04bb12c7f4552f8ced4644ff5d9df

Contents?: true

Size: 1.32 KB

Versions: 13

Compression:

Stored size: 1.32 KB

Contents

# frozen_string_literal: true

module RuboCop
  module Cop
    module Performance
      # This cop identifies uses of `Range#include?`, 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.
      #
      # Here is an example of a case where `Range#cover?` may not provide the
      # desired result:
      #
      #     ('a'..'z').cover?('yellow') # => true
      #
      class RangeInclude < Cop
        MSG = 'Use `Range#cover?` instead of `Range#include?`.'.freeze

        # TODO: If we traced out assignments of variables to their uses, we
        # might pick up on a few more instances of this issue
        # Right now, we only detect direct calls on a Range literal
        # (We don't even catch it if the Range is in double parens)

        def_node_matcher :range_include, <<-END
          (send {irange erange (begin {irange erange})} :include? ...)
        END

        def on_send(node)
          add_offense(node, :selector, MSG) if range_include(node)
        end

        def autocorrect(node)
          ->(corrector) { corrector.replace(node.loc.selector, 'cover?') }
        end
      end
    end
  end
end

Version data entries

13 entries across 13 versions & 2 rubygems

Version Path
dirwatch-0.0.9 vendor/bundle/ruby/2.5.0/gems/rubocop-0.46.0/lib/rubocop/cop/performance/range_include.rb
dirwatch-0.0.8 vendor/bundle/ruby/2.5.0/gems/rubocop-0.46.0/lib/rubocop/cop/performance/range_include.rb
dirwatch-0.0.6 vendor/bundle/ruby/2.3.0/gems/rubocop-0.46.0/lib/rubocop/cop/performance/range_include.rb
dirwatch-0.0.5 vendor/bundle/ruby/2.3.0/gems/rubocop-0.46.0/lib/rubocop/cop/performance/range_include.rb
dirwatch-0.0.4 vendor/bundle/ruby/2.3.0/gems/rubocop-0.46.0/lib/rubocop/cop/performance/range_include.rb
dirwatch-0.0.3 vendor/bundle/ruby/2.3.0/gems/rubocop-0.46.0/lib/rubocop/cop/performance/range_include.rb
dirwatch-0.0.2 vendor/bundle/ruby/2.3.0/gems/rubocop-0.46.0/lib/rubocop/cop/performance/range_include.rb
rubocop-0.47.1 lib/rubocop/cop/performance/range_include.rb
rubocop-0.47.0 lib/rubocop/cop/performance/range_include.rb
rubocop-0.46.0 lib/rubocop/cop/performance/range_include.rb
rubocop-0.45.0 lib/rubocop/cop/performance/range_include.rb
rubocop-0.44.1 lib/rubocop/cop/performance/range_include.rb
rubocop-0.44.0 lib/rubocop/cop/performance/range_include.rb