开发者

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

开发者 https://www.devze.com 2023-02-03 23:55 出处:网络
i have some code in Ruby here below: class A @@lock = Monitor.new class B def method @@lock.synchronize puts \"xxxxx\"

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 c开发者_StackOverflow中文版lass B's method, how to do it? thank you in advance.


I don't think you can without defining an accessor.

Class B is lexically scoped inside of A, so its real name is A::B and various other things are different.

But it's not a child or any other sort of derived class, so it doesn't actually have any special rights to see private or protected or otherwise local elements of A.


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
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号