Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why do both ways of accesing module functions exist in Ruby?

Tags:

ruby

module A
  def self.func
    puts "func"
  end
end

>> A.func
func
>> A::func
func

Why do both . and :: exist? Why not only .?

like image 351
Geo Avatar asked Jun 20 '11 13:06

Geo


People also ask

How do you access a module method in Ruby?

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.

How do you call a module function in Ruby?

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 Ruby?

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).

What are modules used for in Ruby?

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.


1 Answers

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!"
like image 79
maerics Avatar answered Nov 15 '22 09:11

maerics