123456789_123456789_123456789_123456789_123456789_

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

Relationships & Source Files
Super Chains via Extension / Inclusion / Inheritance
Class Chain:
self, AutoCorrector, Base
Instance Chain:
self, Base
Inherits: Base
  • Object
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

Cop Safety Information:

  • This cop is unsafe for novel definitions of map and collect on non-Enumerable objects that do not respond to zip. To make your object enumerable, define an each method as described in https://ruby-doc.org/core/Enumerable.html

Constant Summary

Instance Method Summary

Instance Method Details

#map_with_array?(node)

[ GitHub ]

  
# 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 _)))
  }
PATTERN

#offense_range(node) (private)

[ GitHub ]

  
# File 'lib/rubocop/cop/performance/zip_without_block.rb', line 50

def offense_range(node)
  node.loc.selector.join(node.parent.loc.end)
end

#on_csend(node)

Alias for #on_send.

[ GitHub ]

  
# File 'lib/rubocop/cop/performance/zip_without_block.rb', line 39

alias on_csend on_send

#on_send(node) Also known as: #on_csend

[ GitHub ]

  
# File 'lib/rubocop/cop/performance/zip_without_block.rb', line 34

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

  register_offense(node)
end

#register_offense(node) (private)

[ GitHub ]

  
# File 'lib/rubocop/cop/performance/zip_without_block.rb', line 43

def register_offense(node)
  offense_range = offense_range(node)
  add_offense(offense_range) do |corrector|
    corrector.replace(offense_range, 'zip')
  end
end