Class: RuboCop::Cop::EachReturnValue

Inherits:
Base
  • Object
show all
Extended by:
AutoCorrector
Includes:
RangeHelp
Defined in:
lib/rubocop/cop/each_return_cops.rb

Overview

This cop checks for the use of return values when calling each method.

each method just returns the same object that was originally being called, so it makes no sense to store it in another variable. Most probably the author thought she was calling map and wanted to use the result, this cop helps the developer identify those cases. It can autocorrect this offense by removing the variable and the operator of a lvasgn.

Examples:

# incorrect
value = object.each { |x| x*2 }

# correct
object.each { |x| operation! }
value = object.map { |x| x*2 }

Instance Method Summary collapse

Instance Method Details

#on_lvasgn(node) ⇒ Object



29
30
31
32
33
34
35
36
# File 'lib/rubocop/cop/each_return_cops.rb', line 29

def on_lvasgn(node)
  if array_each?(node)
    add_offense(node, message: 'Do not use the return value of .each') do |corrector|
      corrector.remove(node.loc.name)
      corrector.remove(range_with_surrounding_space(range: node.loc.operator))
    end
  end
end