Sha256: abb83e01a749f9cdd3bb0b43ffeb120217e08b903028b12ce2b5e37d515126f8

Contents?: true

Size: 1.11 KB

Versions: 17

Compression:

Stored size: 1.11 KB

Contents

# frozen_string_literal: true

module RuboCop
  module Cop
    module Performance
      # 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 < Cop
        MSG = 'Use `sort` instead of `sort_by { |%s| %s }`.'.freeze

        def_node_matcher :redundant_sort_by, <<-END
          (block $(send _ :sort_by) (args (arg $_x)) (lvar _x))
        END

        def on_block(node)
          redundant_sort_by(node) do |send, var_name|
            range = sort_by_range(send, node)
            add_offense(node, range, format(MSG, var_name, var_name))
          end
        end

        def autocorrect(node)
          send, = *node
          ->(corrector) { corrector.replace(sort_by_range(send, node), 'sort') }
        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

17 entries across 17 versions & 2 rubygems

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