Class: RuboCop::Cop::Performance::FlatMap

Inherits:
Base
  • Object
show all
Extended by:
AutoCorrector
Includes:
RangeHelp
Defined in:
lib/rubocop/cop/performance/flat_map.rb

Overview

Identifies usages of ‘map { … }.flatten` and change them to use `flat_map { … }` instead.

Examples:

# bad
[1, 2, 3, 4].map { |e| [e, e] }.flatten(1)
[1, 2, 3, 4].collect { |e| [e, e] }.flatten(1)

# good
[1, 2, 3, 4].flat_map { |e| [e, e] }
[1, 2, 3, 4].map { |e| [e, e] }.flatten
[1, 2, 3, 4].collect { |e| [e, e] }.flatten

Constant Summary collapse

MSG =
'Use `flat_map` instead of `%<method>s...%<flatten>s`.'
RESTRICT_ON_SEND =
%i[flatten flatten!].freeze
FLATTEN_MULTIPLE_LEVELS =
' Beware, `flat_map` only flattens 1 level ' \
'and `flatten` can be used to flatten ' \
'multiple levels.'

Instance Method Summary collapse

Instance Method Details

#on_send(node) ⇒ Object Also known as: on_csend



39
40
41
42
43
44
45
46
47
48
# File 'lib/rubocop/cop/performance/flat_map.rb', line 39

def on_send(node)
  flat_map_candidate?(node) do |map_node, first_method, flatten, params|
    flatten_level, = *params.first
    if cop_config['EnabledForFlattenWithoutParams'] && !flatten_level
      offense_for_levels(node, map_node, first_method, flatten)
    elsif flatten_level == 1
      offense_for_method(node, map_node, first_method, flatten)
    end
  end
end