[ruby-core:123645] [Ruby Bug#21662] Variables other than those in the conditional score are replaced.
From:
"nobu (Nobuyoshi Nakada) via ruby-core" <ruby-core@...>
Date:
2025-11-02 10:13:02 UTC
List:
ruby-core #123645
Issue #21662 has been updated by nobu (Nobuyoshi Nakada).
Description updated
Status changed from Open to Feedback
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).
----------------------------------------
Bug #21662: Variables other than those in the conditional score are replaced.
https://bugs.ruby-lang.org/issues/21662#change-115028
* 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/