How to access a class variable of an outer class from an inner class in ruby

I have the code in Ruby below:

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

after starting it gives an error saying that below:

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

if I want to know how to access the external class Class variable @@ lock from the internal method of class B, how to do it? thanks in advance.

+5
source share
2 answers

The only way to access this class variable is through an access method.

class A
   def self.lock
     @@lock ||= Monitor.new
   end

   class B
     def method
       A.lock.synchronize
         puts "xxxxx"
       end
     end
   end
 end
+1
source

I don’t think you can without an accessor definition.

The class is Blexically bounded inside A, so its real name A :: B and various other things are different.

- , A.

+6

All Articles