Sha256: 29cea2db5788b1b3ebcfb944c93560bed0ed45dd0dd50c27fc5867478042b7b1

Contents?: true

Size: 1.1 KB

Versions: 22

Compression:

Stored size: 1.1 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 < Cop
        MSG = 'The argument to each_with_object cannot be immutable.'

        def_node_matcher :each_with_object?, <<~PATTERN
          ({send csend} _ :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

22 entries across 21 versions & 4 rubygems

Version Path
grape-extra_validators-2.0.0 vendor/bundle/ruby/2.6.0/gems/rubocop-0.79.0/lib/rubocop/cop/lint/each_with_object_argument.rb
rubocop-0.88.0 lib/rubocop/cop/lint/each_with_object_argument.rb
rbhint-0.87.1.rc1 lib/rubocop/cop/lint/each_with_object_argument.rb
rubocop-0.87.1 lib/rubocop/cop/lint/each_with_object_argument.rb
rubocop-0.87.0 lib/rubocop/cop/lint/each_with_object_argument.rb
rubocop-0.86.0 lib/rubocop/cop/lint/each_with_object_argument.rb
files.com-1.0.1 vendor/bundle/ruby/2.5.0/gems/rubocop-0.85.1/lib/rubocop/cop/lint/each_with_object_argument.rb
rbhint-0.85.1.rc2 lib/rubocop/cop/lint/each_with_object_argument.rb
rbhint-0.85.1.rc1 lib/rubocop/cop/lint/each_with_object_argument.rb
rubocop-0.85.1 lib/rubocop/cop/lint/each_with_object_argument.rb
rbhint-0.8.5.rc1 lib/rubocop/cop/lint/each_with_object_argument.rb
rubocop-0.85.0 lib/rubocop/cop/lint/each_with_object_argument.rb
rubocop-0.84.0 lib/rubocop/cop/lint/each_with_object_argument.rb
rubocop-0.83.0 lib/rubocop/cop/lint/each_with_object_argument.rb
rubocop-0.82.0 lib/rubocop/cop/lint/each_with_object_argument.rb
rubocop-0.81.0 lib/rubocop/cop/lint/each_with_object_argument.rb
rubocop-0.80.1 lib/rubocop/cop/lint/each_with_object_argument.rb
rubocop-0.80.0 lib/rubocop/cop/lint/each_with_object_argument.rb
grape-extra_validators-1.0.0 vendor/bundle/ruby/2.6.0/gems/rubocop-0.79.0/lib/rubocop/cop/lint/each_with_object_argument.rb
grape-extra_validators-1.0.0 vendor/bundle/ruby/2.4.0/gems/rubocop-0.79.0/lib/rubocop/cop/lint/each_with_object_argument.rb