Documentation I’ve read tells me to use Module.method to access methods in a module. However, I can use Module::method as well. Is this syntactic sugar, or am I confused?
module Cat
FURRY_LEVEL = 4
def self.sound
%w{meow purr hiss zzzz}.sample
end
end
puts Cat.sound # This works.
puts Cat::sound # This also works. Why?!
puts Cat.FURRY_LEVEL # Expected error occurs here.
puts Cat::FURRY_LEVEL # This works.
Constant resolution always requires that you use
::.Method invocation is idiomatically and usually a period (
.), but::is also legal. This is not just true for so-called module methods, but for invoking any method on any object:It’s not so much “syntax sugar” as it is simply alternative syntax, such as the ability to write
iforcasestatements with either a newline,thenand newline, or justthen.It is specifically allowed because Ruby allows methods with the same name as a constant, and sometimes it makes sense to think that they are the same item:
You see this commonly in Ruby in the Nokogiri library, which has (for example) the
Nokogiri::XMLmodule as well as theNokogiri.XMLmethod. When creating an XML document, many people choose to writeYou see this also in the Sequel library, where you can write either:
Again, we have a method (Sequel.Model) named the same as a constant (Sequel::Model). The second line could also be written as
…but it doesn’t look quite as nice.