Code is worth a thousand words: why this code acts as it does?
class MyClass
@variable = 0
class << self
attr_accessor :variable
end
puts variable # => 0, as expected
variable = 1
puts variable # => 1, as expected
puts self.variable # added after @Arup's comments => 0
end
puts MyClass.variable # => 0, as really not expected!
MyClass.variable = 2
puts MyClass.variable # => 2, as expected
For the record, I have read all I could find on metaclasses and 'class is an object' theory, but this still makes no sense to me.
Which variable has been set by variable = 1
from inside the class, and which has been set by MyClass.variable = 2
? How come that accessory is accessible from both inside the class definition and from outside, but it does a different thing?
Or just very simply: what is going on here?