Sha256: 2dfa00497d4158c8984122fed743651d9fc685e13f41e50585b6795a4fa41fa6

Contents?: true

Size: 1.14 KB

Versions: 9

Compression:

Stored size: 1.14 KB

Contents

# frozen_string_literal: true

module RuboCop
  module Cop
    module Lint
      # Checks if each_with_object is called with an immutable
      # argument. Since the argument is the object that the given block shall
      # make calls on to build something based on the enumerable that
      # each_with_object iterates over, an immutable argument makes no sense.
      # It's definitely a bug.
      #
      # @example
      #
      #   # bad
      #   sum = numbers.each_with_object(0) { |e, a| a += e }
      #
      #   # good
      #   num = 0
      #   sum = numbers.each_with_object(num) { |e, a| a += e }
      class EachWithObjectArgument < Base
        MSG = 'The argument to each_with_object cannot be immutable.'
        RESTRICT_ON_SEND = %i[each_with_object].freeze

        # @!method each_with_object?(node)
        def_node_matcher :each_with_object?, <<~PATTERN
          (call _ :each_with_object $_)
        PATTERN

        def on_send(node)
          each_with_object?(node) do |arg|
            return unless arg.immutable_literal?

            add_offense(node)
          end
        end
        alias on_csend on_send
      end
    end
  end
end

Version data entries

9 entries across 9 versions & 1 rubygems

Version Path
rubocop-1.70.0 lib/rubocop/cop/lint/each_with_object_argument.rb
rubocop-1.69.2 lib/rubocop/cop/lint/each_with_object_argument.rb
rubocop-1.69.1 lib/rubocop/cop/lint/each_with_object_argument.rb
rubocop-1.69.0 lib/rubocop/cop/lint/each_with_object_argument.rb
rubocop-1.68.0 lib/rubocop/cop/lint/each_with_object_argument.rb
rubocop-1.67.0 lib/rubocop/cop/lint/each_with_object_argument.rb
rubocop-1.66.1 lib/rubocop/cop/lint/each_with_object_argument.rb
rubocop-1.66.0 lib/rubocop/cop/lint/each_with_object_argument.rb
rubocop-1.65.1 lib/rubocop/cop/lint/each_with_object_argument.rb