Class: RuboCop::Cop::Style::MapIntoArray

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/map_into_array.rb


Checks for usages of each with <<, push, or append which can be replaced by map.

If PreferredMethods is configured for map in Style/CollectionMethods, this cop uses the specified method for replacement.

The return value of Enumerable#each is self, whereas the return value of Enumerable#map is an Array. They are not autocorrected when a return value could be used because these types differ.
It only detects when the mapping destination is a local variable initialized as an empty array and referred to only by the pushing operation. This is because, if not, it’s challenging to statically guarantee that the mapping destination variable remains an empty array:
ret = []
src.each { |e| ret << e * 2 } # `<<` method may mutate `ret`

dest = []
src.each { |e| dest << transform(e, dest) } # `transform` method may mutate `dest`


# bad
dest = []
src.each { |e| dest << e * 2 }

# good
dest = src.map { |e| e * 2 }

# good - contains another operation
dest = []
src.each { |e| dest << e * 2; puts e }

Cop Safety Information:

  • This cop is unsafe because not all objects that have an each method also have a map method (e.g. ENV). Additionally, for calls with a block, not all objects that have a map method return an array (e.g. Enumerator::Lazy).

Constant Summary

::RuboCop::Cop::Base - Inherited


::RuboCop::Cop::RangeHelp - Included


Class Attribute Summary

::RuboCop::Cop::AutoCorrector - Extended

::RuboCop::Cop::Base - Inherited

.gem_requirements, .lint?,

Returns if class supports autocorrect.


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


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



.callbacks_needed, .cop_name, .department,

Returns an url to view this cops documentation online.


Call for abstract Cop classes.


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


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


Register a version requirement for the given gem name.


::RuboCop::ExcludeLimit - Extended


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


Instance Attribute Summary

Instance Method Summary

::RuboCop::Cop::RangeHelp - Included

#add_range, #column_offset_between,

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


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


Adds an offense that has no particular location.


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.


Called before any investigation.


Configuration Helpers.

#cop_name, #excluded_file?,

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


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.


Alias for Base#cop_name.


Called after all on_…​


Called before all on_…​


Called instead of all on_…​


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


Called between investigations.

#relevant_file?, #target_rails_version, #target_ruby_version, #annotate, #apply_correction, #attempt_correction,

Reserved for Cop::Cop.


Called to complete an investigation.

#correct, #current_corrector,

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,

Actually private methods.


::RuboCop::Cop::AutocorrectLogic - Included

::RuboCop::Cop::IgnoredNode - Included

Constructor Details

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

Class Method Details


[ GitHub ]

# File 'lib/rubocop/cop/style/map_into_array.rb', line 71

def self.joining_forces

Instance Method Details

#after_leaving_scope(scope, _variable_table)

[ GitHub ]

# File 'lib/rubocop/cop/style/map_into_array.rb', line 75

def after_leaving_scope(scope, _variable_table)
  (@scopes ||= []) << scope

#correct_push_node(corrector, push_node) (private)

[ GitHub ]

# File 'lib/rubocop/cop/style/map_into_array.rb', line 155

def correct_push_node(corrector, push_node)
  range = push_node.source_range
  arg_range = push_node.first_argument.source_range

  corrector.remove(range_between(range.begin_pos, arg_range.begin_pos))
  corrector.remove(range_between(arg_range.end_pos, range.end_pos))

#correct_return_value_handling(corrector, block, dest_var) (private)

[ GitHub ]

# File 'lib/rubocop/cop/style/map_into_array.rb', line 163

def correct_return_value_handling(corrector, block, dest_var)
  next_node = block.right_sibling

  if lvar_ref?(next_node, dest_var.name)
    corrector.remove(range_with_surrounding_space(next_node.source_range, side: :left))

  corrector.insert_before(block, "#{dest_var.name} = ")

#dest_used_only_for_mapping?(block, dest_var, asgn) ⇒ Boolean (private)

[ GitHub ]

# File 'lib/rubocop/cop/style/map_into_array.rb', line 108

def dest_used_only_for_mapping?(block, dest_var, asgn)
  range = asgn.source_range.join(block.source_range)

  asgn.parent.equal?(block.parent) &&
    dest_var.references.one? { |r| range.contains?(r.node.source_range) } &&
    dest_var.assignments.one? { |a| range.contains?(a.node.source_range) }


[ GitHub ]

# File 'lib/rubocop/cop/style/map_into_array.rb', line 57

def_node_matcher :each_block_with_push?, <<-PATTERN
    ^({begin kwbegin} ...)
    ({block numblock} (send !{nil? self} :each) _
      (send (lvar _) {:<< :push :append} _))


[ GitHub ]

# File 'lib/rubocop/cop/style/map_into_array.rb', line 66

def_node_matcher :empty_array_asgn?, '(lvasgn _ (array))'

#find_closest_assignment(block, dest_var) (private)

[ GitHub ]

# File 'lib/rubocop/cop/style/map_into_array.rb', line 102

def find_closest_assignment(block, dest_var)
  dest_var.assignments.reverse_each.lazy.map(&:node).find do |node|
    node.source_range.end_pos < block.source_range.begin_pos

#find_dest_var(block) (private)

[ GitHub ]

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

def find_dest_var(block)
  node = block.body.receiver
  name = node.children.first

  candidates = @scopes.lazy.filter_map { |s| s.variables[name] }
  candidates.find { |v| v.references.any? { |n| n.node.equal?(node) } }

#lvar_ref?(node, name)

[ GitHub ]

# File 'lib/rubocop/cop/style/map_into_array.rb', line 69

def_node_matcher :lvar_ref?, '(lvar %1)'

#new_method_name (private)

[ GitHub ]

# File 'lib/rubocop/cop/style/map_into_array.rb', line 127

def new_method_name
  default = 'map'
  alternative = config.for_cop('Style/CollectionMethods').dig('PreferredMethods', default)
  alternative || default

#on_block(node) Also known as: #on_numblock

[ GitHub ]

# File 'lib/rubocop/cop/style/map_into_array.rb', line 79

def on_block(node)
  return unless each_block_with_push?(node)

  dest_var = find_dest_var(node)
  return unless (asgn = find_closest_assignment(node, dest_var))
  return unless empty_array_asgn?(asgn)
  return unless dest_used_only_for_mapping?(node, dest_var, asgn)

  register_offense(node, dest_var, asgn)


Alias for #on_block.

[ GitHub ]

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

alias on_numblock on_block

#register_offense(block, dest_var, asgn) (private)

[ GitHub ]

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

def register_offense(block, dest_var, asgn)
  add_offense(block, message: format(MSG, new_method_name: new_method_name)) do |corrector|
    next if return_value_used?(block)

    corrector.replace(block.send_node.selector, new_method_name)
    remove_assignment(corrector, asgn)
    correct_push_node(corrector, block.body)
    correct_return_value_handling(corrector, block, dest_var)

#remove_assignment(corrector, asgn) (private)

[ GitHub ]

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

def remove_assignment(corrector, asgn)
  range = range_with_surrounding_space(asgn.source_range, side: :right)
  range = range_with_surrounding_space(range, side: :right, newlines: false)


#return_value_used?(node) ⇒ Boolean (private)

[ GitHub ]

# File 'lib/rubocop/cop/style/map_into_array.rb', line 133

def return_value_used?(node)
  parent = node.parent

  case parent&.type
  when nil
  when :begin, :kwbegin
    !node.right_sibling && return_value_used?(parent)
  when :block, :numblock