class RuboCop::Cop::Performance::Size
have been assigned to an array or a hash.
TODO: Add advanced detection of variables that could
[1, 2, 3].count { |e| e > 2 }
# good
{a: 1, b: 2, c: 3}.size
# good
[1, 2, 3].size
# good
{a: 1, b: 2, c: 3}.count
# bad
[1, 2, 3].count
# bad
@example
`Array` and ‘Hash` and change them to `size`.
This cop is used to identify usages of `count` on an
def allowed_parent?(node)
def allowed_parent?(node) node && node.block_type? end
def array?(node)
def array?(node) return true if node.array_type? return false unless node.send_type? _, constant = *node.receiver constant == :Array || node.method_name == :to_a end
def autocorrect(node)
def autocorrect(node) ->(corrector) { corrector.replace(node.loc.selector, 'size') } end
def eligible_node?(node)
def eligible_node?(node) return false unless node.method?(:count) && !node.arguments? eligible_receiver?(node.receiver) && !allowed_parent?(node.parent) end
def eligible_receiver?(node)
def eligible_receiver?(node) return false unless node array?(node) || hash?(node) end
def hash?(node)
def hash?(node) return true if node.hash_type? return false unless node.send_type? _, constant = *node.receiver constant == :Hash || node.method_name == :to_h end
def on_send(node)
def on_send(node) return unless eligible_node?(node) add_offense(node, location: :selector) end