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?)
Let’s look at this example. Here
@@xinBaris indeed separate from@@xinFoo.But what happens if
Baris a child ofFoo?In this case,
@@xis the same in both cases, and it is the one declared inFoo.Now, back to your example:
The first line declares class variable in the root scope. Root is a special object
mainwhich is of typeObject. So, essentially, you’re defining a class variable onObjectclass. Since everything is anObject, this is how definition ofMyClassalso inherits@@yand is able to change it.