Dynamically added instance method can not access class variable

This is my code:

class MC
 def initialize
   @x = 5; @@y = 6
 end
 def f
   puts @x
   puts @@y
 end
end

m = MC.new
def m.g; puts @x; puts @@y; end
m.g

This produces (when run in irb)

5
(irb):50: warning: class variable access from toplevel
NameError: uninitialized class variable @@y in Object
from (irb):50:in g' from (irb):51 from /usr/bin/irb:11:in

Calling m.f does not produce an error. Why can I access @@y from f, but
not from g?

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs