(The question has already been posted on the Ruby Forum , but did not raise any answer there).
This is my code:
class MC def initialize @x = 5 @@y = 6 end def f puts @x puts @@y end end m = MC.new mf
mf displays the expected result without errors:
5 6
But this:
def mg puts @x puts @@y end mg
gives:
5 warning: class variable access from toplevel NameError: uninitialized class variable @@y in Object
Why can I access @@y from f , but not from g ?
Mentioning toplevel and Object in warning and error messages puzzles me.
@x prints as 5 , so its environment is MC . This eliminates the possibility that @x and @@y in the definition of mg belong to the top-level environment ( Object ) instead of MC .
Why did I receive an error message?
source share