Project

General

Profile

Actions

Bug #16467

closed

Fetching a class variable with instance_eval fails with NameError

Added by barrettkingram (Barrett Ingram) over 4 years ago. Updated over 4 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) over 4 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

Also available in: Atom PDF

Like0
Like0