Project

General

Profile

Actions

Bug #18927

closed

Can't access class variable directly with class inheritance

Added by jemmai (Jemma Issroff) almost 2 years ago. Updated almost 2 years ago.

Status:
Rejected
Assignee:
-
Target version:
-
[ruby-core:109249]

Description

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?

Actions

Also available in: Atom PDF

Like0
Like0Like0Like0Like0