class RuboCop::Cop::Performance::ReverseEach
items.reverse_each
# good
items.reverse.each
# bad
@example
—-
[1, 2, 3].reverse_each {} #=> [1, 2, 3]
[1, 2, 3].reverse.each {} #=> [3, 2, 1]
—-
[source,ruby]
If the return value is used, it will not be detected because the result will be different.
Identifies usages of ‘reverse.each` and change them to use `reverse_each` instead.
def offense_range(node)
def offense_range(node) range_between(node.children.first.loc.selector.begin_pos, node.loc.selector.end_pos) end
def on_send(node)
def on_send(node) return if use_return_value?(node) reverse_each?(node) do range = offense_range(node) add_offense(range) do |corrector| corrector.replace(range, 'reverse_each') end end end
def use_return_value?(node)
def use_return_value?(node) !!node.ancestors.detect do |ancestor| ancestor.assignment? || ancestor.send_type? || ancestor.return_type? end end