Ruby Dot(.) and Double colon(::) operators

Shaneil
1 min readJan 28, 2022

--

Hello, world!

It's been a while.
Too long, but still learning.
Learnings are all written on scraps of paper and stuck in my head but it’s about time I go back to recording it on here. Overthinking has been one of the reasons for procrastinating really. I have decided to go for small tidbits.

This week I’ll quickly go on about the Dot (.) and Double colon (::) operators.

So, you apparently call a module’s method by putting before its (the method) name, the module’s name and the dot operator(.) ie. module.method_name and when you want to reference a constant you use the module’s name and the double colon operator(::) ie. module::CONSTANT_NAME
The :: operator (properly referred to as a unary operator), allows instance methods, class methods and constants to be called from anywhere outside their module.

Still with me?
A simple example below of calling a constant outside its module. Why not whip out your interactive shell and play around?

BAR = ‘Hello’ #=> global BAR initialization
module Foo
::BAR = 'I am outside in the world' #=> sets the global BAR
BAR = 'I am inside Foo' #=> sets the local BAR
end
puts Foo::BAR => gives us the local BAR in Foo
puts BAR => This will output the global BAR constant

Might get some warnings about constant already initialized but we’re not here for that.

Remember in Ruby, classes and methods may be considered constants too. You’ll need to prefix the constant’s name with the appropriate class or object name etc…

Until next time 🖐

--

--

Shaneil

Software Engineer in London. • Ruby • Rails • Javascript • React (Not so much lately) •TDD