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 @@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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With