如何从ruby中的内部类访问外部类的类变量 [英] how to access a class variable of outer class from inner class in ruby
本文介绍了如何从ruby中的内部类访问外部类的类变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我在下面有一些 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:
A::B 中未初始化的类变量@@lock (NameError)
如果我想知道如何从内部类B的方法访问外部类A的类变量@@lock,该怎么做?提前致谢.
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.
推荐答案
访问这个类变量的唯一方法是通过访问器方法
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
这篇关于如何从ruby中的内部类访问外部类的类变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文