Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does the :: operator work in Ruby?

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
like image 262
mlawsonca Avatar asked Aug 16 '15 17:08

mlawsonca


People also ask

What is the use of :: operator?

In C++, scope resolution operator is ::. It is used for following purposes. 2) To define a function outside a class. 3) To access a class's static variables.

What does :: operator mean in C++?

In programming, an operator is a symbol that operates on a value or a variable. Operators are symbols that perform operations on variables and values. For example, + is an operator used for addition, while - is an operator used for subtraction. Operators in C++ can be classified into 6 types: Arithmetic Operators.

What is the name of this operator === in Ruby?

Triple Equals Operator (More Than Equality) Our last operator today is going to be about the triple equals operator ( === ). This one is also a method, and it appears even in places where you wouldn't expect it to. Ruby is calling the === method here on the class.

What is the & operator in Ruby?

It is called the Safe Navigation Operator. Introduced in Ruby 2.3. 0, it lets you call methods on objects without worrying that the object may be nil (Avoiding an undefined method for nil:NilClass error), similar to the try method in Rails.


1 Answers

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.

like image 91
ndnenkov Avatar answered Nov 15 '22 06:11

ndnenkov