Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Instance methods in modules

Tags:

Consider the following code:

module ModName   def aux     puts 'aux'   end end 

If we replace module with class, we can do the following:

ModName.new.aux 

Modules cannot be instanced, though. Is there a way to call the aux method on the module?

like image 295
freenight Avatar asked Nov 24 '09 01:11

freenight


People also ask

CAN modules have instance variables?

Explanation: Yes, Module instance variables are present in the class when you would include them inside the class.

How do you call a method in a module?

The method definitions look similar, too: Module methods are defined just like class methods. 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 are instance methods in Ruby?

In Ruby, a method provides functionality to an Object. A class method provides functionality to a class itself, while an instance method provides functionality to one instance of a class. We cannot call an instance method on the class itself, and we cannot directly call a class method on an instance.


2 Answers

Think about what aux is. What object will respond to aux? It's an instance method, which means that instances of classes that include ModName will respond to it. The ModName module itself is not an instance of such a class. This would also not work if you had defined ModName as a class — you can't call an instance method without an instance.

Modules are very much like classes that can be mixed into other classes to add behavior. When a class mixes in a module, all of the module's instance methods become instance methods of the class. It's a way of implementing multiple inheritance.

They also serve as substitutes for namespaces, since each module defines a namespace. But that's somewhat unrelated. (Incidentally, classes also have their own namespaces, but making it a class implies that you'll create instances of it, so they're conceptually wrong for that purpose.)

like image 129
Chuck Avatar answered Sep 19 '22 18:09

Chuck


You can do it this way:

module ModName   def aux     puts 'aux'   end   module_function :aux end 

and then just call it:

ModName.aux 
like image 26
pupeno Avatar answered Sep 22 '22 18:09

pupeno