Why do both ways of accesing module functions exist in Ruby?
module A
def self.func
puts "func"
end
end
>> A.func
func
>> A::func
func
Why do both .
and ::
exist? Why not only .
?
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!"
链接地址: http://www.djcxy.com/p/7796.html