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
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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With