From: "jeremyevans0 (Jeremy Evans) via ruby-core" Date: 2024-09-17T14:39:50+00:00 Subject: [ruby-core:119238] [Ruby master Feature#20742] Trying to assign to a variable in statement modifier should emit a warning Issue #20742 has been updated by jeremyevans0 (Jeremy Evans). Earlopain (A S) wrote in #note-5: > Should this just work? If I do: > > ```rb > if a = 0.zero? > p a > end > ``` > > it has no problem with it. I would expect these to be equivalent. Never wrote the one-liner myself, the longer form above I definitly do though When Ruby is parsing/scanning code, and it gets to an expression that could be a local variable or method call, Ruby checks the local variables in scope. If the local variable is already defined, it treats it as a local variable access. If not, it treats it as a method call to self. When you do: ```ruby if a = 0.zero? p a end ``` The `a = 0.zero?` code is parsed/scanned before the `p a` code, and it sets the local variable `a`. When Ruby parses/scans the `p a` code, `a` is a local variable in scope, so it treats it as a local variable. When you do: ```ruby p a if a = 0.zero? ``` Ruby parses/scans the `p a` code before the `a = 0.zero?` code. Since `a` is not a local variable in scope at the time `p a` is parsed, it assumes `a` is a method call to self. ---------------------------------------- Feature #20742: Trying to assign to a variable in statement modifier should emit a warning https://bugs.ruby-lang.org/issues/20742#change-109821 * Author: esad (Esad Hajdarevic) * Status: Open ---------------------------------------- There is an example in Control Expressions documentation: ``` p a if a = 0.zero? # raises NameError ���undefined local variable or method ���a������. ``` However, if we had already defined `a` there would be no exception raised. If one uses something like `p` for scratch variable, due to Kernel#p, also no exception is raised. Statement modifier is generally somewhat inverting the code flow (the right part is evaluated first then the left part), so it is not really obvious why binding variables shouldn't follow the same flow. A warning would be very beneficial. -- https://bugs.ruby-lang.org/ ______________________________________________ ruby-core mailing list -- ruby-core@ml.ruby-lang.org To unsubscribe send an email to ruby-core-leave@ml.ruby-lang.org ruby-core info -- https://ml.ruby-lang.org/mailman3/lists/ruby-core.ml.ruby-lang.org/