5

I am new to Ruby and am 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 
1
  • 5
    Because you call puts 5 times? Commented Aug 16, 2015 at 17:09

1 Answer 1

7

If you remove the last line, you will see that you will get 5, 4, 3, 2. The reason is that the body of classes and modules is just regular code (unlike in some other languages). Therefore, those print statements will be executed when the classes/modules are getting parsed.

As to how :: works - it just lets you move around the scopes. ::A will reference the A in the main scope. Just A will refer to A in the current scope. A::B will refer to the B, that is inside the A, that is inside the current scope.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.