Class: RuboCop::Cop::Elegant::NoRedundantVariable
- Inherits:
-
Base
- Object
- Base
- RuboCop::Cop::Elegant::NoRedundantVariable
- 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.
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
Instance Method Summary collapse
Instance Method Details
#on_def(node) ⇒ Object
38 39 40 |
# File 'lib/rubocop/cop/elegant/no_redundant_variable.rb', line 38 def on_def(node) check(node.body) end |
#on_defs(node) ⇒ Object
42 43 44 |
# File 'lib/rubocop/cop/elegant/no_redundant_variable.rb', line 42 def on_defs(node) check(node.body) end |