Project

General

Profile

Actions

Misc #15364

closed

Suppress "shadowing outer local variable" warning for assignments e.g. with "tap"

Added by svoop (Sven Schwyn) over 5 years ago. Updated over 5 years ago.

Status:
Closed
Assignee:
-
[ruby-core:90209]

Description

The following pattern is quite common when initializing a complex object where some attributes (attr1 and 2) can be set by the initializer, whereas others (attr3 and 4) cannot:

# the local variable "thing" does not exist up to this point
thing = Thing.new(
  attr1: 'foo',
  attr2: 'bar',
).tap do |thing|
  attr3 = 'foz',
  attr4 = 'baz'
end

The syntax check with ruby -cw won't like this:

warning: shadowing outer local variable - thing

While a very useful warning in many situations, it is obsolete when the outer local variable doesn't exist up to this point and therefore no collision with the inner local variable of the same name can occur.

Of course, just change the inner variable name to silence the warning, but for the sake of readable code, it should be okay to "recycle" the same variable name both outer and inner (since they refer to the same thing).

(I don't know whether the syntax check is capable of telling whether "thing" is defined already or not though.)

Actions

Also available in: Atom PDF

Like0
Like0Like0Like0