From: "jeremyevans0 (Jeremy Evans) via ruby-core" Date: 2024-09-16T15:48:26+00:00 Subject: [ruby-core:119225] [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). Eregon (Benoit Daloze) wrote in #note-2: > jeremyevans0 (Jeremy Evans) wrote in #note-1: > > Assigning in post-conditionals is a fairly common in Ruby. > > Is it? I don't think I've seen that often or maybe even never. The pattern is used in the standard library. Here's a list of assignments in post-conditionals that don't use parentheses around the assignment (significantly more use parentheses around the assignment): ```ruby lib/net/http.rb: arg.pop if opt = Hash.try_convert(arg[-1]) lib/rubygems/request_set/lockfile/tokenizer.rb: pos = s.pos if leading_whitespace = s.scan(/ +/) lib/optparse.rb: str << " (#{v})" if v = release lib/optparse.rb: argv.unshift(arg) if arg = catch(:terminate) { ``` The optparse ones looked questionable, but I checked and the code for both is safe as the local variable is already in scope. So maybe "fairly common" is a stretch, but it's used enough that that I don't think we should warn about it, unless we can limit the warnings to the cases that are actually problematic. ---------------------------------------- Feature #20742: Trying to assign to a variable in statement modifier should emit a warning https://bugs.ruby-lang.org/issues/20742#change-109803 * 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/