Felipe Araujo Felipe Araujo - 2 years ago 82
Ruby Question

Module vs methods outside module

I would like to know what the difference is between using a module with methods inside it and using a simple file with many methods without creating a module, like the example below:

def doStuff
puts 'test';

module Example
def self.doStuff
puts 'test';

I could require both files and use the methods inside one. I want to know why I should create a module instead of having just a bunch of methods inside a

Answer Source

Modules allow you group your methods and you can include them in other modules and classes. You can include module methods into the module/class itself or its eigenclass. So, with modules you have more flexibility. Not to mention that you are not cluttering up the "global" namespace.

Also, when you define method in a file, you are defining it in the current context. Since, everything in Ruby is an object, you are actually defining it within a main object (an instance of Object class).

2.3.0 :001 > self
 => main 
2.3.0 :002 > self.class
 => Object 
2.3.0 :003 > self.object_id
 => 70123533022000 
2.3.0 :004 > def test; end;
2.3.0 :005 > self.public_methods.include? :test
 => true
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download