forked from rubocop/rubocop
/
redundant_with_index.rb
80 lines (70 loc) · 1.84 KB
/
redundant_with_index.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
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
# frozen_string_literal: true
module RuboCop
module Cop
module Lint
# Checks for redundant `with_index`.
#
# @example
# # bad
# ary.each_with_index do |v|
# v
# end
#
# # good
# ary.each do |v|
# v
# end
#
# # bad
# ary.each.with_index do |v|
# v
# end
#
# # good
# ary.each do |v|
# v
# end
#
class RedundantWithIndex < Base
include RangeHelp
extend AutoCorrector
MSG_EACH_WITH_INDEX = 'Use `each` instead of `each_with_index`.'
MSG_WITH_INDEX = 'Remove redundant `with_index`.'
def on_block(node)
return unless (send = redundant_with_index?(node))
range = with_index_range(send)
add_offense(range, message: message(send)) do |corrector|
if send.method?(:each_with_index)
corrector.replace(send.loc.selector, 'each')
else
corrector.remove(range)
corrector.remove(send.loc.dot)
end
end
end
alias on_numblock on_block
private
# @!method redundant_with_index?(node)
def_node_matcher :redundant_with_index?, <<~PATTERN
{
(block
$(send _ {:each_with_index :with_index} ...)
(args (arg _)) ...)
(numblock
$(send _ {:each_with_index :with_index} ...) 1 ...)
}
PATTERN
def message(node)
if node.method?(:each_with_index)
MSG_EACH_WITH_INDEX
else
MSG_WITH_INDEX
end
end
def with_index_range(send)
range_between(send.loc.selector.begin_pos, send.loc.expression.end_pos)
end
end
end
end
end