Class: RuboCop::Cop::Performance::SelectMap

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

Overview

In Ruby 2.7, ‘Enumerable#filter_map` has been added.

This cop identifies places where ‘select.map` can be replaced by `filter_map`.

Examples:

# bad
ary.select(&:foo).map(&:bar)
ary.filter(&:foo).map(&:bar)

# good
ary.filter_map { |o| o.bar if o.foo }

Constant Summary collapse

MSG =
'Use `filter_map` instead of `%<method_name>s.map`.'
RESTRICT_ON_SEND =
%i[select filter].freeze

Instance Method Summary collapse

Instance Method Details

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



27
28
29
30
31
32
33
34
35
36
# File 'lib/rubocop/cop/performance/select_map.rb', line 27

def on_send(node)
  return if (first_argument = node.first_argument) && !first_argument.block_pass_type?
  return unless (send_node = map_method_candidate(node))
  return unless send_node.method?(:map)

  map_method = send_node.parent&.block_type? ? send_node.parent : send_node

  range = offense_range(node, map_method)
  add_offense(range, message: format(MSG, method_name: node.method_name))
end