Felipe Araujo Felipe Araujo - 2 years ago 100
Ruby Question

Module vs Function Outside Module in Ruby

I would like to know what is the difference if I use a Module with functions inside it and a simple file with many functions without creating a module, like the example below:

def doStuff
puts 'test';

module Example
def self.doStuff
puts 'test';

As far as I know I could require both files and use the methods inside it one, so I wanna know why I should create a Module instead of having just a bunch of functions inside a .rb file.

Thanks in advance!

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