module A
def self.func
puts "func"
end
end
>> A.func
func
>> A::func
func
Why do both .
and ::
exist? Why not only .
?
The module methods & instance methods can be accessed by both extend & include keyword. Regardless of which keyword you use extend or include : the only way to access the module methods is by Module_name::method_name.
As with class methods, you call a module method by preceding its name with the module's name and a period, and you reference a constant using the module name and two colons.
What is the difference between a class and a module? Modules are collections of methods and constants. They cannot generate instances. Classes may generate instances (objects), and have per-instance state (instance variables).
Modules are one of the shiniest resources of Ruby because they provide two great benefits: we can create namespaces to prevent name clashes and we can use them as mixins to share code across the application. Similar to classes, with modules we also group methods and constants and share code.
The scope resolution operator (::
) can resolve constants, instance methods, and class methods, so we can use that operator for essentially any method as long as we are looking in the right place.
Additionally, since the method "func" is defined as a class method of module A (by self.func
, analogous to a "static" method) it belongs directly to the module (which is itself an object) so it can be called with the dot operator with the module as the receiver. Note that instances of module A do not have any visibility to "func", since it is a class method:
aye = Object.new.extend(A)
aye::func # raises NoMethodError
aye.func # raises NoMethodError
If the method was defined as an instance method then it could only be called with the dot operator on instances of the module.
module B
def func2
puts "OK!"
end
end
B::func2 # raises NoMethodError
B.func2 # raises NoMethodError
bee = Object.new.extend(B)
bee::func2 # "OK!"
bee.func2 # "OK!"
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