123456789_123456789_123456789_123456789_123456789_

Class: RuboCop::Cop::Style::RedundantSort

Relationships & Source Files
Super Chains via Extension / Inclusion / Inheritance
Class Chain:
self, ::RuboCop::Cop::AutoCorrector, ::RuboCop::Cop::Base, ::RuboCop::ExcludeLimit, NodePattern::Macros, RuboCop::AST::Sexp
Instance Chain:
Inherits: RuboCop::Cop::Base
Defined in: lib/rubocop/cop/style/redundant_sort.rb

Overview

Identifies instances of sorting and then taking only the first or last element. The same behavior can be accomplished without a relatively expensive sort by using Enumerable#min instead of sorting and taking the first element and Enumerable#max instead of sorting and taking the last element. Similarly, Enumerable#min_by and Enumerable#max_by can replace Enumerable#sort_by calls after which only the first or last element is used.

Examples:

# bad
[2, 1, 3].sort.first
[2, 1, 3].sort[0]
[2, 1, 3].sort.at(0)
[2, 1, 3].sort.slice(0)

# good
[2, 1, 3].min

# bad
[2, 1, 3].sort.last
[2, 1, 3].sort[-1]
[2, 1, 3].sort.at(-1)
[2, 1, 3].sort.slice(-1)

# good
[2, 1, 3].max

# bad
arr.sort_by(&:foo).first
arr.sort_by(&:foo)[0]
arr.sort_by(&:foo).at(0)
arr.sort_by(&:foo).slice(0)

# good
arr.min_by(&:foo)

# bad
arr.sort_by(&:foo).last
arr.sort_by(&:foo)[-1]
arr.sort_by(&:foo).at(-1)
arr.sort_by(&:foo).slice(-1)

# good
arr.max_by(&:foo)

Cop Safety Information:

  • This cop is unsafe, because sort…​last and max may not return the same element in all cases.

    In an enumerable where there are multiple elements where a <⇒ b == 0, or where the transformation done by the sort_by block has the same result, sort.last and max (or sort_by.last and max_by) will return different elements. sort.last will return the last element but max will return the first element.

    For example:

    class MyString < String; end
    strings = [MyString.new('test'), 'test']
    strings.sort.last.class   #=> String
    strings.max.class         #=> MyString
    words = %w(dog horse mouse)
    words.sort_by { |word| word.length }.last   #=> 'mouse'
    words.max_by { |word| word.length }         #=> 'horse'

Constant Summary

::RuboCop::Cop::Base - Inherited

EMPTY_OFFENSES, RESTRICT_ON_SEND

::RuboCop::Cop::RangeHelp - Included

BYTE_ORDER_MARK, NOT_GIVEN

Class Attribute Summary

::RuboCop::Cop::AutoCorrector - Extended

::RuboCop::Cop::Base - Inherited

.gem_requirements, .lint?,
.support_autocorrect?

Returns if class supports autocorrect.

.support_multiple_source?

Override if your cop should be called repeatedly for multiple investigations Between calls to on_new_investigation and on_investigation_end, the result of processed_source will remain constant.

Class Method Summary

::RuboCop::Cop::Base - Inherited

.autocorrect_incompatible_with

List of cops that should not try to autocorrect at the same time as this cop.

.badge

Naming.

.callbacks_needed, .cop_name, .department,
.documentation_url

Returns a url to view this cops documentation online.

.exclude_from_registry

Call for abstract Cop classes.

.inherited,
.joining_forces

Override and return the Force class(es) you need to join.

.match?

Returns true if the cop name or the cop namespace matches any of the given names.

.new,
.requires_gem

Register a version requirement for the given gem name.

.restrict_on_send

::RuboCop::ExcludeLimit - Extended

exclude_limit

Sets up a configuration option to have an exclude limit tracked.

transform

Instance Attribute Summary

Instance Method Summary

::RuboCop::Cop::RangeHelp - Included

#add_range, #column_offset_between,
#contents_range

A range containing only the contents of a literal with delimiters (e.g.

#directions,
#effective_column

Returns the column attribute of the range, except if the range is on the first line and there’s a byte order mark at the beginning of that line, in which case 1 is subtracted from the column value.

#final_pos, #move_pos, #move_pos_str, #range_between, #range_by_whole_lines, #range_with_comments, #range_with_comments_and_lines, #range_with_surrounding_comma, #range_with_surrounding_space, #source_range

::RuboCop::Cop::Base - Inherited

#add_global_offense

Adds an offense that has no particular location.

#add_offense

Adds an offense on the specified range (or node with an expression) Unless that offense is disabled for this range, a corrector will be yielded to provide the cop the opportunity to autocorrect the offense.

#begin_investigation

Called before any investigation.

#callbacks_needed,
#cop_config

Configuration Helpers.

#cop_name, #excluded_file?,
#external_dependency_checksum

This method should be overridden when a cop’s behavior depends on state that lives outside of these locations:

#inspect,
#message

Gets called if no message is specified when calling add_offense or add_global_offense Cops are discouraged to override this; instead pass your message directly.

#name

Alias for Base#cop_name.

#offenses,
#on_investigation_end

Called after all on_…​

#on_new_investigation

Called before all on_…​

#on_other_file

Called instead of all on_…​

#parse

There should be very limited reasons for a Cop to do it’s own parsing.

#parser_engine,
#ready

Called between investigations.

#relevant_file?,
#target_gem_version

Returns a gems locked versions (i.e.

#target_rails_version, #target_ruby_version, #annotate, #apply_correction, #attempt_correction,
#callback_argument

Reserved for Cop::Cop.

#complete_investigation

Called to complete an investigation.

#correct, #current_corrector,
#current_offense_locations

Reserved for Commissioner:

#current_offenses, #currently_disabled_lines, #custom_severity, #default_severity, #disable_uncorrectable, #enabled_line?, #file_name_matches_any?, #find_message, #find_severity, #range_for_original, #range_from_node_or_range,
#reset_investigation

Actually private methods.

#use_corrector

::RuboCop::Cop::AutocorrectLogic - Included

::RuboCop::Cop::IgnoredNode - Included

Constructor Details

This class inherits a constructor from RuboCop::Cop::Base

Instance Method Details

#accessor_start(node) (private)

This gets the start of the accessor whether it has a dot (e.g. .first) or doesn’t (e.g. [0])

[ GitHub ]

  
# File 'lib/rubocop/cop/style/redundant_sort.rb', line 193

def accessor_start(node)
  if node.loc.dot
    node.loc.dot.begin_pos
  else
    node.loc.selector.begin_pos
  end
end

#arg_node(node) (private)

[ GitHub ]

  
# File 'lib/rubocop/cop/style/redundant_sort.rb', line 183

def arg_node(node)
  node.first_argument
end

#arg_value(node) (private)

[ GitHub ]

  
# File 'lib/rubocop/cop/style/redundant_sort.rb', line 187

def arg_value(node)
  arg_node(node)&.node_parts&.first
end

#autocorrect(corrector, node, sort_node, sorter, accessor) (private)

[ GitHub ]

  
# File 'lib/rubocop/cop/style/redundant_sort.rb', line 148

def autocorrect(corrector, node, sort_node, sorter, accessor)
  # Remove accessor, e.g. `first` or `[-1]`.
  corrector.remove(range_between(accessor_start(node), node.source_range.end_pos))
  # Replace "sort" or "sort_by" with the appropriate min/max method.
  corrector.replace(sort_node.loc.selector, suggestion(sorter, accessor, arg_value(node)))
  # Replace to avoid syntax errors when followed by a logical operator.
  replace_with_logical_operator(corrector, node) if with_logical_operator?(node)
end

#base(accessor, arg) (private)

[ GitHub ]

  
# File 'lib/rubocop/cop/style/redundant_sort.rb', line 166

def base(accessor, arg)
  if accessor == :first || arg&.zero?
    'min'
  elsif accessor == :last || arg == -1
    'max'
  end
end

#find_redundant_sort(*nodes) (private)

[ GitHub ]

  
# File 'lib/rubocop/cop/style/redundant_sort.rb', line 115

def find_redundant_sort(*nodes)
  nodes.each do |node|
    if (sort_node, sorter, accessor = redundant_sort?(node))
      return [node, sort_node, sorter, accessor]
    end
  end

  nil
end

#message(node, sorter, accessor) (private)

[ GitHub ]

  
# File 'lib/rubocop/cop/style/redundant_sort.rb', line 136

def message(node, sorter, accessor)
  accessor_source = range_between(
    node.loc.selector.begin_pos,
    node.source_range.end_pos
  ).source

  format(MSG,
         suggestion: suggestion(sorter, accessor, arg_value(node)),
         sorter: sorter,
         accessor_source: accessor_source)
end

#offense_range(sort_node, node) (private)

[ GitHub ]

  
# File 'lib/rubocop/cop/style/redundant_sort.rb', line 132

def offense_range(sort_node, node)
  range_between(sort_node.loc.selector.begin_pos, node.source_range.end_pos)
end

#on_csend(node)

Alias for #on_send.

[ GitHub ]

  
# File 'lib/rubocop/cop/style/redundant_sort.rb', line 111

alias on_csend on_send

#on_send(node) Also known as: #on_csend

[ GitHub ]

  
# File 'lib/rubocop/cop/style/redundant_sort.rb', line 104

def on_send(node)
  ancestor, sort_node, sorter, accessor =
    find_redundant_sort(node.parent, node.parent&.parent)
  return unless ancestor

  register_offense(ancestor, sort_node, sorter, accessor)
end

#redundant_sort?(node)

[ GitHub ]

  
# File 'lib/rubocop/cop/style/redundant_sort.rb', line 88

def_node_matcher :redundant_sort?, <<~MATCHER
  {
    (call $(call _ $:sort) ${:last :first})
    (call $(call _ $:sort) ${:[] :at :slice} {(int 0) (int -1)})

    (call $(call _ $:sort_by _) ${:last :first})
    (send $(send _ $:sort_by _) ${:[] :at :slice} {(int 0) (int -1)})

    (call ({block numblock} $(call _ ${:sort_by :sort}) ...) ${:last :first})
    (call
      ({block numblock} $(call _ ${:sort_by :sort}) ...)
      ${:[] :at :slice} {(int 0) (int -1)}
    )
  }
MATCHER

#register_offense(node, sort_node, sorter, accessor) (private)

[ GitHub ]

  
# File 'lib/rubocop/cop/style/redundant_sort.rb', line 125

def register_offense(node, sort_node, sorter, accessor)
  message = message(node, sorter, accessor)
  add_offense(offense_range(sort_node, node), message: message) do |corrector|
    autocorrect(corrector, node, sort_node, sorter, accessor)
  end
end

#replace_with_logical_operator(corrector, node) (private)

[ GitHub ]

  
# File 'lib/rubocop/cop/style/redundant_sort.rb', line 157

def replace_with_logical_operator(corrector, node)
  corrector.insert_after(node.child_nodes.first, " #{node.parent.loc.operator.source}")
  corrector.remove(node.parent.loc.operator)
end

#suffix(sorter) (private)

[ GitHub ]

  
# File 'lib/rubocop/cop/style/redundant_sort.rb', line 174

def suffix(sorter)
  case sorter
  when :sort
    ''
  when :sort_by
    '_by'
  end
end

#suggestion(sorter, accessor, arg) (private)

[ GitHub ]

  
# File 'lib/rubocop/cop/style/redundant_sort.rb', line 162

def suggestion(sorter, accessor, arg)
  base(accessor, arg) + suffix(sorter)
end

#with_logical_operator?(node) ⇒ Boolean (private)

[ GitHub ]

  
# File 'lib/rubocop/cop/style/redundant_sort.rb', line 201

def with_logical_operator?(node)
  return false unless (parent = node.parent)

  parent.operator_keyword?
end