Sha256: b8982d0208adafc7557bf1995df442c0e67f216d079ce27f6563cdb602727489

Contents?: true

Size: 1.19 KB

Versions: 14

Compression:

Stored size: 1.19 KB

Contents

# frozen_string_literal: true

module RuboCop
  module Cop
    module Lint
      # This cop 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 }
      #
      # @example
      #
      #   # 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

14 entries across 14 versions & 3 rubygems

Version Path
scrapbook-0.3.2 vendor/ruby/2.7.0/gems/rubocop-1.26.0/lib/rubocop/cop/lint/each_with_object_argument.rb
scrapbook-0.3.1 vendor/ruby/2.7.0/gems/rubocop-1.26.0/lib/rubocop/cop/lint/each_with_object_argument.rb
rubocop-1.29.1 lib/rubocop/cop/lint/each_with_object_argument.rb
rubocop-1.29.0 lib/rubocop/cop/lint/each_with_object_argument.rb
rubocop-1.28.2 lib/rubocop/cop/lint/each_with_object_argument.rb
rubocop-1.28.1 lib/rubocop/cop/lint/each_with_object_argument.rb
rubocop-1.28.0 lib/rubocop/cop/lint/each_with_object_argument.rb
rubocop-1.27.0 lib/rubocop/cop/lint/each_with_object_argument.rb
rubocop-1.26.1 lib/rubocop/cop/lint/each_with_object_argument.rb
op_connect-0.1.2 vendor/bundle/ruby/3.1.0/gems/rubocop-1.26.0/lib/rubocop/cop/lint/each_with_object_argument.rb
rubocop-1.26.0 lib/rubocop/cop/lint/each_with_object_argument.rb
rubocop-1.25.1 lib/rubocop/cop/lint/each_with_object_argument.rb
rubocop-1.25.0 lib/rubocop/cop/lint/each_with_object_argument.rb
rubocop-1.24.1 lib/rubocop/cop/lint/each_with_object_argument.rb