Jwan622
Jwan622

Reputation: 11639

instance methods of classes vs module methods

I am reading this explanation of module methods for Ruby and how they are different from instance methods for classes. Here is the explanation I am reading:

Remember that unlike an instance method, a module method needs to be defined on the module itself. How do you access the module? Recall that inside a module definition, self refers to the module being defined. So you'll need to define the method using the form self.xxx.

I don't totally get it. When we defined methods inside Classes, we didn't have to define it on the class itself. We merely called it on the instantiated objects of the classes.

Why do we need to define module methods on the module itself using the term "self"? What's the purpose of this? Why can't we just define module methods without using the term self? Here is how my module skeleton looks:

module GameTurn

    def self.take_turn(player)

    end

Upvotes: 3

Views: 1726

Answers (1)

tadman
tadman

Reputation: 211560

There's two kinds of module methods:

  • Those that are intended to be mixed in to other modules or classes: "Mixins"
  • Those that are intended to be used directly: "Exposed Methods"

For example:

module Example
  def self.exposed_method
    # This method is called as Example.exposed_Method
  end

  def mixin_method
    # This method must be imported somewhere else with include or extend
    # or it cannot be used.
  end
end

You have two on a class as well:

  • Those that are called only on instances of the class: "Instance methods"
  • Those that are called directly on the class: "Class methods"
    • These are also called "static methods" in other languages.

Example:

class ExampleClass
  def self.class_method
    # This can be called as ExampleClass.class_method
  end

   def instance_method
     # This can only be called on an instance: ExampleClass.new.instance_method
   end
end

Upvotes: 7

Related Questions