Class: RuboCop::Cop::Elegant::NoRedundantVariable

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

Overview

Forbids local variables that are assigned exactly once and then referenced exactly once, since such variables can be inlined at the place of their single use without loss of clarity. The cop inspects each method body in isolation, ignores compound assignments (+=, ||=, &&=), multiple assignments, for loops, rescue variables, and assignments embedded into expressions such as if or while conditions; only top-level statements of a sequence are considered. A variable whose single read sits inside a context that does not also enclose the assignment is left alone: loops or blocks (block, numblock, while, until, for) so that inlining does not move the right-hand side into a hot path, and conditional branches (if, case, case_match, and, or, rescue, resbody, ensure) so that inlining does not change whether or when the right-hand side is evaluated. A variable that is reassigned, read more than once, or never read is left alone too.

Auto-correct inlines the redundant assignment: it replaces the single lvar read with the source of the assignment’s right-hand side, then removes the whole assignment line including its leading indent and trailing newline. The right-hand side is wrapped in parentheses unless it is already a primary expression (literal, variable, parenthesized expression, or method call with parentheses or no arguments), so that operator precedence at the read site is preserved.

Constant Summary collapse

MSG =
'Variable "%<name>s" is redundant and must be inlined: it is read only once'
STATEMENT_PARENTS =
%i[begin kwbegin def defs block numblock].freeze
LOOP_TYPES =
%i[block numblock while until while_post until_post for].freeze
ALWAYS_FIRST_TYPES =
%i[if case case_match and or].freeze
ALWAYS_HOIST_TYPES =
%i[rescue resbody ensure].freeze
PRIMARY_TYPES =
%i[
  int float str sym dstr dsym xstr true false nil array hash regexp
  lvar ivar cvar gvar const self nth_ref back_ref
].freeze

Instance Method Summary collapse

Instance Method Details

#on_def(node) ⇒ Object



56
57
58
# File 'lib/rubocop/cop/elegant/no_redundant_variable.rb', line 56

def on_def(node)
  check(node.body)
end

#on_defs(node) ⇒ Object



60
61
62
# File 'lib/rubocop/cop/elegant/no_redundant_variable.rb', line 60

def on_defs(node)
  check(node.body)
end