Adi Pradhan

home

Ruby scope resolution operator without a prefix. The double colon with a prefix

17 Jun 2014

Ruby has a scope resolution operation :: the double-colon and is very straightforward to use:

module A
  modules B 
  	MY_CONSTANT = 'test'
  end
end

puts A::B::MY_CONSTANT # 'test'

Great, that’s a well namespaced constant. But, what if you need to refer to a constant on the outer namespace (global namespace) from the module ?

Easy…

MY_CONSTANT = 'on the global scope'
module A
  modules B 
  	MY_CONSTANT = 'test'
  	puts MY_CONSTANT 	   # returns 'test'
  	puts A::B::MY_CONSTANT # returns 'test'
  	puts ::MY_CONSTANT	   # returns 'on the global scope'
  end
end

puts A::B::MY_CONSTANT # 'test'
puts MY_CONSTANT 	   # 'on the global scope'
puts ::MY_CONSTANT     # 'on the global scope'
comments powered by Disqus