123456789_123456789_123456789_123456789_123456789_

Class: RuboCop::Cop::Style::ReduceToHash

Relationships & Source Files
Super Chains via Extension / Inclusion / Inheritance
Class Chain:
Instance Chain:
Inherits: RuboCop::Cop::Base
Defined in: lib/rubocop/cop/style/reduce_to_hash.rb

Overview

Checks for each_with_object, inject, and reduce calls that build a hash from an enumerable, where to_h with a block could be used instead.

This cop complements Style/HashTransformKeys and Style/HashTransformValues, which handle hash-to-hash transformations with destructured key-value pairs. This cop targets the case where a hash is built from individual elements (non-destructured block parameter).

Examples:

# bad
array.each_with_object({}) { |elem, hash| hash[elem.id] = elem.name }

# bad
array.inject({}) { |hash, elem| hash[elem.id] = elem.name; hash }

# bad
array.reduce({}) { |hash, elem| hash[elem.id] = elem.name; hash }

# bad
array.each_with_object({}) { |elem, hash| hash[elem] = elem.to_s }

# good
array.to_h { |elem| [elem.id, elem.name] }

# good
array.to_h { |elem| [elem, elem.to_s] }

Cop Safety Information:

  • This cop is unsafe because it cannot guarantee that the receiver is an Enumerable by static analysis, so the correction may not be actually equivalent. Additionally, each_with_object returns the hash object while to_h returns a new hash, which could matter if the hash object identity is important.

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::TargetRubyVersion - Extended

::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,
#arguments_range

A range containing the first to the last argument of a method call or method definition.

#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

#accumulator_name(block_node) (private)

[ GitHub ]

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

def accumulator_name(block_node)
  index = block_node.method?(:each_with_object) ? 1 : 0
  block_node.argument_list[index].name
end

#accumulator_used_in_expressions?(block_node, key, value) ⇒ Boolean (private)

[ GitHub ]

  
# File 'lib/rubocop/cop/style/reduce_to_hash.rb', line 106

def accumulator_used_in_expressions?(block_node, key, value)
  acc_name = accumulator_name(block_node)
  references_variable?(key, acc_name) || references_variable?(value, acc_name)
end

#adjusted_source(expr_node, block_node) (private)

[ GitHub ]

  
# File 'lib/rubocop/cop/style/reduce_to_hash.rb', line 169

def adjusted_source(expr_node, block_node)
  source = expr_node.source
  return source unless block_node.numblock_type?
  return source if block_node.method?(:each_with_object)

  # For inject/reduce numblocks, _2 is the element (becomes _1)
  source.gsub('_2', '_1')
end

#check_offense(node, block_node) (private)

[ GitHub ]

  
# File 'lib/rubocop/cop/style/reduce_to_hash.rb', line 94

def check_offense(node, block_node)
  key, value = if node.method?(:each_with_object)
                 each_with_object_to_hash?(block_node)
               else
                 inject_to_hash?(block_node)
               end
  return unless key
  return if accumulator_used_in_expressions?(block_node, key, value)

  register_offense(node, block_node, key, value)
end

#do_end_replacement(block_node, body, arg = nil) (private)

[ GitHub ]

  
# File 'lib/rubocop/cop/style/reduce_to_hash.rb', line 152

def do_end_replacement(block_node, body, arg = nil)
  args = arg ? " |#{arg}|" : ''
  "to_h do#{args}\n#{indent(block_node)}  #{body}\n#{indent(block_node)}end"
end

#each_with_object_to_hash?(node)

each_with_object({}) { |elem, hash| hash[key] = value }

[ GitHub ]

  
# File 'lib/rubocop/cop/style/reduce_to_hash.rb', line 52

def_node_matcher :each_with_object_to_hash?, <<~PATTERN
  {
    (block
      (call _ :each_with_object (hash))
      (args (arg _elem) (arg _hash))
      (send (lvar _hash) :[]= $_key $_value))
    (numblock
      (call _ :each_with_object (hash))
      2
      (send (lvar :_2) :[]= $_key $_value))
  }
PATTERN

#element_arg_source(block_node) (private)

[ GitHub ]

  
# File 'lib/rubocop/cop/style/reduce_to_hash.rb', line 161

def element_arg_source(block_node)
  if block_node.method?(:each_with_object)
    block_node.first_argument.source
  else
    block_node.arguments[1].source
  end
end

#indent(node) (private)

[ GitHub ]

  
# File 'lib/rubocop/cop/style/reduce_to_hash.rb', line 178

def indent(node)
  ' ' * node.source_range.column
end

#inject_to_hash?(node)

inject/reduce({}) { |hash, elem| hash[key] = value; hash }

[ GitHub ]

  
# File 'lib/rubocop/cop/style/reduce_to_hash.rb', line 67

def_node_matcher :inject_to_hash?, <<~PATTERN
  {
    (block
      (call _ {:inject :reduce} (hash))
      (args (arg _hash) (arg _elem))
      (begin
        (send (lvar _hash) :[]= $_key $_value)
        (lvar _hash)))
    (numblock
      (call _ {:inject :reduce} (hash))
      2
      (begin
        (send (lvar :_1) :[]= $_key $_value)
        (lvar :_1)))
  }
PATTERN

#named_block_replacement(block_node, body) (private)

[ GitHub ]

  
# File 'lib/rubocop/cop/style/reduce_to_hash.rb', line 143

def named_block_replacement(block_node, body)
  arg = element_arg_source(block_node)
  if block_node.braces?
    "to_h { |#{arg}| #{body} }"
  else
    do_end_replacement(block_node, body, arg)
  end
end

#on_csend(node)

Alias for #on_send.

[ GitHub ]

  
# File 'lib/rubocop/cop/style/reduce_to_hash.rb', line 90

alias on_csend on_send

#on_send(node) Also known as: #on_csend

[ GitHub ]

  
# File 'lib/rubocop/cop/style/reduce_to_hash.rb', line 84

def on_send(node)
  block_node = node.block_node
  return unless block_node

  check_offense(node, block_node)
end

#references_variable?(node, name) ⇒ Boolean (private)

[ GitHub ]

  
# File 'lib/rubocop/cop/style/reduce_to_hash.rb', line 116

def references_variable?(node, name)
  node.each_node(:lvar).any? { |lvar| lvar.children.first == name }
end

#register_offense(send_node, block_node, key_expr, value_expr) (private)

[ GitHub ]

  
# File 'lib/rubocop/cop/style/reduce_to_hash.rb', line 120

def register_offense(send_node, block_node, key_expr, value_expr)
  message = format(MSG, method: send_node.method_name)

  add_offense(send_node.loc.selector, message: message) do |corrector|
    corrector.replace(
      replacement_range(send_node, block_node),
      replacement(block_node, key_expr, value_expr)
    )
  end
end

#replacement(block_node, key_expr, value_expr) (private)

[ GitHub ]

  
# File 'lib/rubocop/cop/style/reduce_to_hash.rb', line 131

def replacement(block_node, key_expr, value_expr)
  key_source = adjusted_source(key_expr, block_node)
  value_source = adjusted_source(value_expr, block_node)
  body = "[#{key_source}, #{value_source}]"

  if block_node.numblock_type?
    block_node.braces? ? "to_h { #{body} }" : do_end_replacement(block_node, body)
  else
    named_block_replacement(block_node, body)
  end
end

#replacement_range(send_node, block_node) (private)

[ GitHub ]

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

def replacement_range(send_node, block_node)
  range_between(send_node.loc.selector.begin_pos, block_node.source_range.end_pos)
end