Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Meaning of Syntax for Ruby Module

Tags:

ruby

I've been going through some tutorials to find this information, but haven't seen anything that directly addresses it.

I've seen several times on modules the following syntax:

module MyModule

   def run()
      puts "running"
   end
end

I've also seen syntax that looks like this:

module MyModule

   def MyModule.run()
      puts "running"
   end
end

What's the advantage to including the module name before the method and vice versa?

like image 964
Cannon Moyer Avatar asked Apr 22 '26 17:04

Cannon Moyer


2 Answers

module MyModule
   def MyModule.run()
      puts "running"
   end
end

is exactly the same as:

module MyModule
   def self.run()
      puts "running"
   end
end

Usually def self.run is used, because it's better when you have to change the module name and it's more idiomatic. I don't see any advantages in writing def MyModule.run.

like image 126
mdesantis Avatar answered Apr 25 '26 09:04

mdesantis


This has nothing to do with modules. This is just normal method definition syntax.

The syntax for a method definition in Ruby is

def <target>.<selector>(<parameters>)
  # …
end

For example:

def foo.bar(baz)
end

This will define a method named bar on the object referenced by foo (more precisely, in the singleton class of the object referenced by foo), with a single mandatory positional parameter whose binding is named baz.

Like with message sends, you can leave out the target, and Ruby will use an implicit default. In a message send, the implicit default is self, with a method definition, the default is the so-called default definee, which is usually the closest lexically enclosing module definition body.

So,

def MyModule.run

means "define a method named run on the object MyModule (or more precisely in the singleton class of the object MyModule)", whereas

def run

means "define a method named run in the default definee", i.e. the closest lexically enclosing module definition body, which in this case is MyModule.

The second version defines run as an instance method of MyModule, the first version defines run as an instance method of the singleton class of MyModule, which we sometimes call a "module method" or "module function".

Note that the first version is usually more idiomatically written as

def self.run
like image 43
Jörg W Mittag Avatar answered Apr 25 '26 09:04

Jörg W Mittag



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!