Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 307
ywenbo Avatar asked Jan 14 '11 06:01

ywenbo


People also ask

Can inner class access outer class variables?

Java inner class is associated with the object of the class and they can access all the variables and methods of the outer class.

Can an inner class use methods of an outer class?

An instance of InnerClass can exist only within an instance of OuterClass and has direct access to the methods and fields of its enclosing instance. To instantiate an inner class, you must first instantiate the outer class.

Can outer class access inner class private?

Conclusion. Outer classes can access inner class private members in Java until a non-static member accesses it from a static context or an inaccessible scope. Inner classes can access the variables of the outer class, including the private instance variables.

How do you define a class variable in Ruby?

Ruby Class VariablesClass variables begin with @@ and must be initialized before they can be used in method definitions. Referencing an uninitialized class variable produces an error. Class variables are shared among descendants of the class or module in which the class variables are defined.


1 Answers

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.

like image 161
DigitalRoss Avatar answered Oct 05 '22 12:10

DigitalRoss