Sha256: 0032f080c23dce4938fe0d9b874b462c82f3184b9e107a3ed02fa81dd32cf389

Contents?: true

Size: 1.51 KB

Versions: 6

Compression:

Stored size: 1.51 KB

Contents

# encoding: utf-8

module RuboCop
  module Cop
    module Performance
      # 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.
      class Size < Cop
        MSG = 'Use `size` instead of `count`.'

        def on_send(node)
          receiver, method, args = *node

          return if receiver.nil?
          return unless method == :count
          return unless array?(receiver) || hash?(receiver)
          return if node.parent && node.parent.block_type?
          return if args && args.block_pass_type?

          add_offense(node, node.loc.selector)
        end

        def autocorrect(node)
          ->(corrector) { corrector.replace(node.loc.selector, 'size') }
        end

        private

        def array?(node)
          receiver, method = *node
          _, constant = *receiver

          node.array_type? || constant == :Array || method == :to_a
        end

        def hash?(node)
          receiver, method = *node
          _, constant = *receiver

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

Version data entries

6 entries across 6 versions & 1 rubygems

Version Path
rubocop-0.34.2 lib/rubocop/cop/performance/size.rb
rubocop-0.34.1 lib/rubocop/cop/performance/size.rb
rubocop-0.34.0 lib/rubocop/cop/performance/size.rb
rubocop-0.33.0 lib/rubocop/cop/performance/size.rb
rubocop-0.32.1 lib/rubocop/cop/performance/size.rb
rubocop-0.32.0 lib/rubocop/cop/performance/size.rb