2

Please explain why self is used in def self.included (klass) below.

module A
  def self.included(klass)
    puts "A -> #{klass}"
    puts A
    puts self
  end
end

class X
  include A
end

2 Answers 2

4

By writing def self.included you are defining a method that is part of the singleton class of module A. In general, singleton methods can only be called by doing A.included() but this singleton method has a special name included that causes the Ruby interpreter to call when the module gets included in to a class.

A normal method in a module (defined with def foo) can only be called if the module gets included in to something else.

Sign up to request clarification or add additional context in comments.

Comments

1

This is how you declare a module method that can be called directly. Normally methods defined within a module are only usable if another class or module includes them, like class X in this example.

module Example
  def self.can_be_called
    true
  end

  def must_be_included
    true
  end
end

In this case you will see these results:

Example.can_be_called
# => true

Example.must_be_included
# => NoMethodError: undefined method `must_be_included' for Example:Module

The self declared methods are not merged in to the classes or modules that include it, though. They are special-purpose that way.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.