Bug #17348
closedShadowed method can not be evaluated on the line that it is shadowed
Description
I encountered this in the code a junior Rubyist wrote. Rewriting to more logical code solved our problem, but in my opinion it should not have been an error. I reduced the code to this:
Expected: nil
Got:
Traceback (most recent call last):
shadowed.rb:4:in `<main>': undefined method `[]' for nil:NilClass (NoMethodError)
Note that:
Does work as expected, so it is specifically when a method is shadowed that this unexpected behaviour occurs.
Updated by jeremyevans0 (Jeremy Evans) over 5 years ago
- Status changed from Open to Rejected
This isn't a bug. It's expected that Ruby scans code and as soon as it encounters a local variable definition (the left hand side of =) it adds it to the local variable table. Changing this to not set the local variable until after the completion of the assignment expression would break code such as:
You can compare to the equivalent that didn't set the local variable until after:
Updated by marcandre (Marc-Andre Lafortune) over 5 years ago
In Ruby 3, you can write a[0] => a and that works :-)