Class: RuboCop::Cop::Performance::ZipWithoutBlock

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

Overview

Checks for ‘map { |id| [id] }` and suggests replacing it with `zip`.

Examples:

# bad
[1, 2, 3].map { |id| [id] }

# good
[1, 2, 3].zip

Constant Summary collapse

MSG =
'Use `zip` without a block argument instead.'
RESTRICT_ON_SEND =
Set.new(%i[map collect]).freeze

Instance Method Summary collapse

Instance Method Details

#map_with_array?(node) ⇒ Object



27
28
29
30
31
32
33
# File 'lib/rubocop/cop/performance/zip_without_block.rb', line 27

def_node_matcher :map_with_array?, <<~PATTERN
  {
    (block (call !nil? RESTRICT_ON_SEND) (args (arg _)) (array (lvar _)))
    (numblock (call !nil? RESTRICT_ON_SEND) 1 (array (lvar _)))
    (itblock (call !nil? RESTRICT_ON_SEND) :it (array (lvar _)))
  }
PATTERN

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



35
36
37
38
39
# File 'lib/rubocop/cop/performance/zip_without_block.rb', line 35

def on_send(node)
  return unless map_with_array?(node.parent)

  register_offense(node)
end