metaprogramming - Ruby class variables in metaclass -


i have ruby class this:

class c   @@v = 1    class << self     p @@v  # goes here   end end  class << c   # here exception    # `singletonclass': uninitialized class variable @@v in object (nameerror)   # a.rb:5:in `<main>'    p @@v end 

my question is: exception said 'uninitialized class variable @@v in object (nameerror)', why ruby lookups class variables in object(main)?

it seems ruby lookups metaclass' class variables outside it.

you have defined class variable @@v class c. shouldn't surprised this:

class << c   p @@v end 

raises exception, because here dealing singleton class of c, have not defined class variable @@v.

the real question is, why work when way?

class c   @@v = 1    class << self     p @@v   end end 

the answer appears that, convenience, whenever access singleton of class from inside class, ruby transparently gives access class's class variables.

note works consistently when define methods well, whether use class << self; def method_name syntax or def self.method_name syntax:

# assuming @@v in c 1 class c   def self.print_v_from_inside     p @@v   end end  def c.print_v_from_outside   p @@v end  c.print_v_from_inside # => 1  c.print_v_from_outside # => nameerror: uninitialized class variable @@v in object 

Comments