Sha256: f858a1db0695b1222508ac2047aca9641204c1a6ae892e5c6fcdfc6ec20dda65

Contents?: true

Size: 1.14 KB

Versions: 41

Compression:

Stored size: 1.14 KB

Contents

# frozen_string_literal: true

module RuboCop
  module Cop
    module Style
      # This cop identifies places where `sort_by { ... }` can be replaced by
      # `sort`.
      #
      # @example
      #   # bad
      #   array.sort_by { |x| x }
      #   array.sort_by do |var|
      #     var
      #   end
      #
      #   # good
      #   array.sort
      class RedundantSortBy < Base
        include RangeHelp
        extend AutoCorrector

        MSG = 'Use `sort` instead of `sort_by { |%<var>s| %<var>s }`.'

        # @!method redundant_sort_by(node)
        def_node_matcher :redundant_sort_by, <<~PATTERN
          (block $(send _ :sort_by) (args (arg $_x)) (lvar _x))
        PATTERN

        def on_block(node)
          redundant_sort_by(node) do |send, var_name|
            range = sort_by_range(send, node)

            add_offense(range, message: format(MSG, var: var_name)) do |corrector|
              corrector.replace(range, 'sort')
            end
          end
        end

        private

        def sort_by_range(send, node)
          range_between(send.loc.selector.begin_pos, node.loc.end.end_pos)
        end
      end
    end
  end
end

Version data entries

41 entries across 41 versions & 6 rubygems

Version Path
scrapbook-0.3.2 vendor/ruby/2.7.0/gems/rubocop-1.26.0/lib/rubocop/cop/style/redundant_sort_by.rb
scrapbook-0.3.1 vendor/ruby/2.7.0/gems/rubocop-1.26.0/lib/rubocop/cop/style/redundant_sort_by.rb
rubocop-1.29.1 lib/rubocop/cop/style/redundant_sort_by.rb
rubocop-1.29.0 lib/rubocop/cop/style/redundant_sort_by.rb
rubocop-1.28.2 lib/rubocop/cop/style/redundant_sort_by.rb
rubocop-1.28.1 lib/rubocop/cop/style/redundant_sort_by.rb
rubocop-1.28.0 lib/rubocop/cop/style/redundant_sort_by.rb
rubocop-1.27.0 lib/rubocop/cop/style/redundant_sort_by.rb
rubocop-1.26.1 lib/rubocop/cop/style/redundant_sort_by.rb
op_connect-0.1.2 vendor/bundle/ruby/3.1.0/gems/rubocop-1.26.0/lib/rubocop/cop/style/redundant_sort_by.rb
rubocop-1.26.0 lib/rubocop/cop/style/redundant_sort_by.rb
rubocop-1.25.1 lib/rubocop/cop/style/redundant_sort_by.rb
rubocop-1.25.0 lib/rubocop/cop/style/redundant_sort_by.rb
phillipug-foodie-0.1.0 .vendor/ruby/3.0.0/gems/rubocop-1.24.0/lib/rubocop/cop/style/redundant_sort_by.rb
rubocop-1.24.1 lib/rubocop/cop/style/redundant_sort_by.rb
rubocop-1.24.0 lib/rubocop/cop/style/redundant_sort_by.rb
rubocop-1.23.0 lib/rubocop/cop/style/redundant_sort_by.rb
rubocop-1.22.3 lib/rubocop/cop/style/redundant_sort_by.rb
rubocop-1.22.2 lib/rubocop/cop/style/redundant_sort_by.rb
rubocop-1.22.1 lib/rubocop/cop/style/redundant_sort_by.rb