[ruby-core:123655] [Ruby Bug#21662] Variables other than those in the conditional score are replaced.
From:
"binh (binh chau) via ruby-core" <ruby-core@...>
Date:
2025-11-03 00:03:27 UTC
List:
ruby-core #123655
Issue #21662 has been updated by binh (binh chau).
nobu (Nobuyoshi Nakada) wrote in #note-1:
> I try to guesstimate your intension by telepathy.
>
> binh (binh chau) wrote:
> > ```ruby
> > def bug!
> > if !bar.is_a?(Bar)
> > bar = ''
> > elsif bar.name == 'bar'
> > end
> > end
> > ```
>
> You might had expected the third `bar` is a `Bar`.
>
> In fact, the first `bar` in `!bar.is_a?(Bar)` is the attribute.
> But the assignment in the next line makes the local variable `bar` regardless whether this line is executed.
> So all `bar` after here in this method, including in the next `elsif` line, are this local variable, that is an empty string or `nil` (when the `elsif` condition is executed).
It looks like a trap.
----------------------------------------
Bug #21662: Variables other than those in the conditional score are replaced.
https://bugs.ruby-lang.org/issues/21662#change-115037
* Author: binh (binh chau)
* Status: Feedback
* ruby -v: 3.2.2
* Backport: 3.2: UNKNOWN, 3.3: UNKNOWN, 3.4: UNKNOWN
----------------------------------------
```ruby
class Bar
attr_accessor :name
end
class Foo
attr_accessor :bar
def initialize(bar=nil)
@bar = bar || Bar.new
end
def bug!
if !bar.is_a?(Bar)
bar = ''
elsif bar.name == 'bar'
end
end
end
Foo.new.bug!
```
--
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/