From: pkmuldoon@... Date: 2021-02-10T09:41:57+00:00 Subject: [ruby-core:102442] [Ruby master Bug#17619] if false foo=42; end creates a foo local variable set to nil Issue #17619 has been updated by pkmuldoon (Phil Muldoon). pkmuldoon (Phil Muldoon) wrote in #note-3: > The second code example is incorrect, it should read > > ``` > 1] pry(main)> defined?(bar) > nil > > [2] pry(main)> if true > [2] pry(main)* bar = 99 > [2] pry(main)* end > > [3] pry(main)> defined?(bar) > "local-variable" > > [5] pry(main)> bar > 99 > ``` zverok (Victor Shepelev) wrote in #note-2: > To the best of my understanding, `if` doesn't create its own scope with its own local variables. So this `if` means for the interpreter that "local variable `bar` is present in current scope" (just not assigned). Okay, but why would a variable be created in a program-flow primitive ie (if etc) if that condition is such that that code is never executed? ---------------------------------------- Bug #17619: if false foo=42; end creates a foo local variable set to nil https://bugs.ruby-lang.org/issues/17619#change-90325 * Author: pkmuldoon (Phil Muldoon) * Status: Open * Priority: Normal * Backport: 2.5: UNKNOWN, 2.6: UNKNOWN, 2.7: UNKNOWN, 3.0: UNKNOWN ---------------------------------------- Take this following code ``` [1] pry(main)> defined?(foo) nil [2] pry(main)> if false [2] pry(main)* foo = 42 [2] pry(main)* end [3] pry(main)> defined?(foo) "local-variable" ``` The inner scope inherits the parent scope (ok) but also modifies the parent scope even if the child scope is never entered. A lesser effect of this: ``` [1] pry(main)> defined?(bar) nil [2] pry(main)> if false [2] pry(main)* bar = 99 [2] pry(main)* end [3] pry(main)> defined?(bar) "local-variable" [5] pry(main)> bar 99 ``` That somewhat lesser affecting because I can just about accept a variable invading the parent scope, and existing after, as a hoisting event. But surely that should not be the case in the negative program-flow case? The side effects of this are defined?(foo) can't be trusted anymore. Apologies if this bug has been filed. I did search for it, but couldn't find anything quite matching it. Thanks! -- https://bugs.ruby-lang.org/ Unsubscribe: