forked from rubocop/rubocop
/
each_with_object_argument.rb
42 lines (38 loc) · 1.11 KB
/
each_with_object_argument.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
# 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 can not be immutable.'.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