Project

General

Profile

Actions

Bug #16467

closed

Fetching a class variable with instance_eval fails with NameError

Bug #16467: Fetching a class variable with instance_eval fails with NameError

Added by barrettkingram (Barrett Ingram) almost 6 years ago. Updated almost 6 years ago.

Status:
Rejected
Assignee:
-
Target version:
-
ruby -v:
ruby 2.7.0p0 (2019-12-25 revision 647ee6f091) [x86_64-darwin18]
[ruby-core:96586]

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 Actions #1 [ruby-core:96591]

  • 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

Also available in: PDF Atom