[#109207] [Ruby master Feature#18915] New error class: NotImplementedYetError or scope change for NotImplementedYet — Quintasan <noreply@...>
Issue #18915 has been reported by Quintasan (Michał Zając).
18 messages
2022/07/14
[ruby-core:109252] [Ruby master Bug#18927] Can't access class variable directly with class inheritance
From:
"mame (Yusuke Endoh)" <noreply@...>
Date:
2022-07-20 01:43:40 UTC
List:
ruby-core #109252
Issue #18927 has been updated by mame (Yusuke Endoh).
Status changed from Open to Rejected
Once a class variable is declared (initialized) in the lexical context of Child, it can only be accessed from the lexical context of Child and its subclasses. Otherwise, any class variable would be accessible from the context of Object, which is the same as a global variable.
> It's best to avoid using class variables completely in Ruby.
Agreed.
----------------------------------------
Bug #18927: Can't access class variable directly with class inheritance
https://bugs.ruby-lang.org/issues/18927#change-98384
* Author: jemmai (Jemma Issroff)
* Status: Rejected
* Priority: Normal
* ruby -v: 3.1.2
* Backport: 2.7: UNKNOWN, 3.0: UNKNOWN, 3.1: UNKNOWN
----------------------------------------
If a child class inherits from a parent class, and the child class sets a class variable, the parent class can't access the class variable literal:
```
class Parent
def self.class_var
puts @@class_var
end
end
class Child < Parent
@@class_var = "class_var"
end
Child.class_var
# => test.rb:3:in `class_var': uninitialized class variable @@class_var in Parent (NameError)
```
Confusingly, if we use `class_variable_get` (method lookup) to access `@@class_var`, we can access it as expected. We can alter the snippet from above to see this behavior:
```
class Parent
def self.class_var
puts class_variable_get(:@@class_var)
puts @@class_var
end
end
class Child < Parent
@@class_var = "class_var"
end
Child.class_var
# => "class_var"
# => test.rb:4:in `class_var': uninitialized class variable @@class_var in Parent (NameError)
```
## Is this desired behavior?
`self` is the subclass so it seems like the class variable should be looked up on the receiver. Why is the method lookup resolution different than the literal? Should it be different?
--
https://bugs.ruby-lang.org/
Unsubscribe: <mailto:ruby-core-request@ruby-lang.org?subject=unsubscribe>
<http://lists.ruby-lang.org/cgi-bin/mailman/options/ruby-core>