Sha256: 79cebbdfa6e921d5d8c84eac0726ae9df6bac59b8551a7991f159faaee394983

Contents?: true

Size: 1.2 KB

Versions: 27

Compression:

Stored size: 1.2 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
          ({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

27 entries across 27 versions & 4 rubygems

Version Path
phillipug-foodie-0.1.0 .vendor/ruby/3.0.0/gems/rubocop-1.24.0/lib/rubocop/cop/lint/each_with_object_argument.rb
rubocop-1.24.0 lib/rubocop/cop/lint/each_with_object_argument.rb
rubocop-1.23.0 lib/rubocop/cop/lint/each_with_object_argument.rb
rubocop-1.22.3 lib/rubocop/cop/lint/each_with_object_argument.rb
rubocop-1.22.2 lib/rubocop/cop/lint/each_with_object_argument.rb
rubocop-1.22.1 lib/rubocop/cop/lint/each_with_object_argument.rb
rubocop-1.22.0 lib/rubocop/cop/lint/each_with_object_argument.rb
rubocop-1.21.0 lib/rubocop/cop/lint/each_with_object_argument.rb
rubocop-1.20.0 lib/rubocop/cop/lint/each_with_object_argument.rb
rubocop-1.19.1 lib/rubocop/cop/lint/each_with_object_argument.rb
rails_mini_profiler-0.2.0 vendor/bundle/ruby/3.0.0/gems/rubocop-1.18.3/lib/rubocop/cop/lint/each_with_object_argument.rb
rubocop-1.19.0 lib/rubocop/cop/lint/each_with_object_argument.rb
rubocop-1.18.4 lib/rubocop/cop/lint/each_with_object_argument.rb
rubocop-1.18.3 lib/rubocop/cop/lint/each_with_object_argument.rb
rubocop-1.18.2 lib/rubocop/cop/lint/each_with_object_argument.rb
rubocop-1.18.1 lib/rubocop/cop/lint/each_with_object_argument.rb
rubocop-1.18.0 lib/rubocop/cop/lint/each_with_object_argument.rb
rubocop-1.17.0 lib/rubocop/cop/lint/each_with_object_argument.rb
rubocop-1.16.1 lib/rubocop/cop/lint/each_with_object_argument.rb
rubocop-1.16.0 lib/rubocop/cop/lint/each_with_object_argument.rb