Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fully understanding Ruby class variable

Tags:

ruby

In this code block,

@@y = 1
class MyClass
 @@y = 2
end
p @@y # => 2

naively, it seems that @@y is in top-level scope, and it isn't the same @@y as the one in MyClass's scope. Why is @@y affected by the class MyClass definition? (why is the result 2?)

like image 291
sploiber Avatar asked Jul 19 '26 12:07

sploiber


1 Answers

Let's look at this example. Here @@x in Bar is indeed separate from @@x in Foo.

class Foo
  @@x = 1
end

class Bar
  @@x = 2
end

Foo.class_variable_get(:@@x) # => 1
Bar.class_variable_get(:@@x) # => 2

But what happens if Bar is a child of Foo?

class Foo
  @@x = 1
end

class Bar < Foo
  @@x = 2
end

Foo.class_variable_get(:@@x) # => 2
Bar.class_variable_get(:@@x) # => 2

In this case, @@x is the same in both cases, and it is the one declared in Foo.

Now, back to your example:

@@y = 1
class MyClass
  @@y = 2
end
p @@y

The first line declares class variable in the root scope. Root is a special object main which is of type Object. So, essentially, you're defining a class variable on Object class. Since everything is an Object, this is how definition of MyClass also inherits @@y and is able to change it.

like image 112
Sergio Tulentsev Avatar answered Jul 21 '26 02:07

Sergio Tulentsev