Sha256: e1c3dc27ce2c17a043c796f9279d962d542defc201180bf948feaeb7504043b8

Contents?: true

Size: 1.16 KB

Versions: 30

Compression:

Stored size: 1.16 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

        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

30 entries across 30 versions & 2 rubygems

Version Path
plaid-14.13.0 vendor/bundle/ruby/3.0.0/gems/rubocop-0.91.1/lib/rubocop/cop/lint/each_with_object_argument.rb
plaid-14.12.1 vendor/bundle/ruby/3.0.0/gems/rubocop-0.91.1/lib/rubocop/cop/lint/each_with_object_argument.rb
plaid-14.12.0 vendor/bundle/ruby/2.6.0/gems/rubocop-0.91.1/lib/rubocop/cop/lint/each_with_object_argument.rb
plaid-14.11.1 vendor/bundle/ruby/2.6.0/gems/rubocop-0.91.1/lib/rubocop/cop/lint/each_with_object_argument.rb
plaid-14.10.0 vendor/bundle/ruby/2.6.0/gems/rubocop-0.91.1/lib/rubocop/cop/lint/each_with_object_argument.rb
plaid-14.7.0 vendor/bundle/ruby/2.6.0/gems/rubocop-0.91.1/lib/rubocop/cop/lint/each_with_object_argument.rb
rubocop-1.10.0 lib/rubocop/cop/lint/each_with_object_argument.rb
rubocop-1.9.1 lib/rubocop/cop/lint/each_with_object_argument.rb
rubocop-1.9.0 lib/rubocop/cop/lint/each_with_object_argument.rb
rubocop-1.8.1 lib/rubocop/cop/lint/each_with_object_argument.rb
rubocop-1.8.0 lib/rubocop/cop/lint/each_with_object_argument.rb
rubocop-1.7.0 lib/rubocop/cop/lint/each_with_object_argument.rb
rubocop-1.6.1 lib/rubocop/cop/lint/each_with_object_argument.rb
rubocop-1.6.0 lib/rubocop/cop/lint/each_with_object_argument.rb
rubocop-1.5.2 lib/rubocop/cop/lint/each_with_object_argument.rb
rubocop-1.5.1 lib/rubocop/cop/lint/each_with_object_argument.rb
rubocop-1.5.0 lib/rubocop/cop/lint/each_with_object_argument.rb
rubocop-1.4.2 lib/rubocop/cop/lint/each_with_object_argument.rb
rubocop-1.4.1 lib/rubocop/cop/lint/each_with_object_argument.rb
rubocop-1.4.0 lib/rubocop/cop/lint/each_with_object_argument.rb