How does the :: operator work in Ruby?

I am new to Ruby and confused by the :: operator. Why does the following code output 2, 3, 4, 5, 1, and not just output 1? Thanks!

 class C a = 5 module M a = 4 module N a = 3 class D a = 2 def show_a a = 1 puts a end puts a end puts a end puts a end puts a end d = C::M::N::D.new d.show_a 
+5
source share
1 answer

If you delete the last line, you will see that you get 5, 4, 3, 2 . The reason is that the body of classes and modules is regular code (unlike some other languages). Therefore, these print instructions will be executed when classes / modules are processed.

How it works :: - it just allows you to navigate areas. ::A will refer to A in the main area. Just A will refer to A in the current area. A::B will refer to B , which is inside A , which is inside the current region.

+5
source

All Articles