Mary Rose Cook Mary Rose Cook - 1 month ago 6
Ruby Question

Why can't a class instance variable be accessed in a singleton-class definition in Ruby?

class MyClass
@my_class_instance_variable = "here"

p @my_class_instance_variable # => "here"

class << self
p @my_class_instance_variable # => nil
end
end

class MyClass
p @my_class_instance_variable # => "here"
end


Why does the second
p
print
nil
, when the third
p
prints
"here"
? My understanding of a singleton class definition (
class << self
) is that it has the same scope as a class definition (
class MyClass
).

(This question has a similar title, but it has a different focus.)

Answer

My understanding of a singleton class definition (class << self) is that it has the same scope as a class definition

Nope. The scope is different. You defined @my_class_instance_variable in the scope of MyClass, but are trying to access it in the scope if MyClass's singleton class.

It is as easy to check as:

class Foo
  puts self #=> Foo

  class << self
    puts self #=> #<Class:Foo>
  end
end

With the output of:

Foo
#<Class:Foo>
Comments