Actions
Bug #16467
closedFetching a class variable with instance_eval fails with NameError
    Bug #16467:
    Fetching a class variable with instance_eval fails with NameError
  
Status:
Rejected
Assignee:
-
Target version:
-
ruby -v:
ruby 2.7.0p0 (2019-12-25 revision 647ee6f091) [x86_64-darwin18]
Backport:
Description
Trying to fetch a class variable using instance_eval fails with uninitialized class variable @variable_name in Object (NameError).
Reproduction program:
class FooClass
  def initialize
    @foo = "foo"
    @@bar = "bar"
  end
  def get_bar
    @@bar
  end
end
foo = FooClass.new
puts foo.instance_eval("@foo") # prints "foo"
puts foo.get_bar # prints "bar"
puts foo.instance_eval("@@bar") # raises uninitialized class variable @@bar in Object (NameError)
        
           Updated by nobu (Nobuyoshi Nakada) almost 6 years ago
          Updated by nobu (Nobuyoshi Nakada) almost 6 years ago
          
          
        
        
      
      - Status changed from Open to Rejected
Class variables need to be in the proper class context.
The following code raises a NameError too.
class FooClass::BarClass
  @@bar # NameError (uninitialized class variable @@bar in FooClass::BarClass)
end
You have to use class_eval.
foo.class.class_eval("@@bar")
# or
FooClass.class_eval("@@bar")
Actions