Search code examples
rubyclass-variables

how to access a class variable of outer class from inner class in ruby


i have some code in Ruby here below:

class A
  @@lock = Monitor.new
  class B
    def method
      @@lock.synchronize
        puts "xxxxx"
      end
    end
  end
end    

after running it throws an error which said that below:

uninitialized class variable @@lock in A::B (NameError)

if i want to know how to access the outer class A's class variable @@lock from inner class B's method, how to do it? thank you in advance.


Solution

  • The only way to access this class variable is via an accessor method

    class A
       def self.lock
         @@lock ||= Monitor.new
       end
    
       class B
         def method
           A.lock.synchronize
             puts "xxxxx"
           end
         end
       end
     end