class RuboCop::Cop::Performance::Size

This cop is used to identify usages of `count` on an `Array` and `Hash` and change them to `size`.

@example

# bad
[1, 2, 3].count

# bad
{a: 1, b: 2, c: 3}.count

# good
[1, 2, 3].size

# good
{a: 1, b: 2, c: 3}.size

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

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

Constants

MSG

Public Instance Methods

on_send(node) click to toggle source
# File lib/rubocop/cop/performance/size.rb, line 28
def on_send(node)
  return unless eligible_node?(node)

  add_offense(node, location: :selector)
end

Private Instance Methods

allowed_parent?(node) click to toggle source
# File lib/rubocop/cop/performance/size.rb, line 52
def allowed_parent?(node)
  node && node.block_type?
end
array?(node) click to toggle source
# File lib/rubocop/cop/performance/size.rb, line 56
def array?(node)
  _, constant = *node.receiver

  node.array_type? || constant == :Array || node.method_name == :to_a
end
autocorrect(node) click to toggle source
# File lib/rubocop/cop/performance/size.rb, line 36
def autocorrect(node)
  ->(corrector) { corrector.replace(node.loc.selector, 'size') }
end
eligible_node?(node) click to toggle source
# File lib/rubocop/cop/performance/size.rb, line 40
def eligible_node?(node)
  return false unless node.method?(:count) && !node.arguments?

  eligible_receiver?(node.receiver) && !allowed_parent?(node.parent)
end
eligible_receiver?(node) click to toggle source
# File lib/rubocop/cop/performance/size.rb, line 46
def eligible_receiver?(node)
  return false unless node

  array?(node) || hash?(node)
end
hash?(node) click to toggle source
# File lib/rubocop/cop/performance/size.rb, line 62
def hash?(node)
  _, constant = *node.receiver

  node.hash_type? || constant == :Hash || node.method_name == :to_h
end