123456789_123456789_123456789_123456789_123456789_

Class: RuboCop::Cop::Performance::Size

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

Overview

Identifies usages of count on an Array and Hash and change them to size.

TODO: Add advanced detection of variables that could have been assigned to an array or a hash.

Examples:

# bad
[1, 2, 3].count
(1..3).to_a.count
Array[*1..3].count
Array(1..3).count

# bad
{a: 1, b: 2, c: 3}.count
[[:foo, :bar], [1, 2]].to_h.count
Hash[*('a'..'z')].count
Hash(key: :value).count

# good
[1, 2, 3].size
(1..3).to_a.size
Array[*1..3].size
Array(1..3).size

# good
{a: 1, b: 2, c: 3}.size
[[:foo, :bar], [1, 2]].to_h.size
Hash[*('a'..'z')].size
Hash(key: :value).size

# good
[1, 2, 3].count { |e| e > 2 }

Constant Summary

Instance Method Summary

Instance Method Details

#on_csend(node)

Alias for #on_send.

[ GitHub ]

  
# File 'lib/rubocop/cop/performance/size.rb', line 72

alias on_csend on_send

#on_send(node) Also known as: #on_csend

[ GitHub ]

  
# File 'lib/rubocop/cop/performance/size.rb', line 65

def on_send(node)
  return if node.parent&.block_type? || !count?(node)

  add_offense(node.loc.selector) do |corrector|
    corrector.replace(node.loc.selector, 'size')
  end
end