Application 2024-05-15

About Ruby Modules

Understand Ruby modules for namespacing, mixin multiple inheritance, and providing common methods without class instantiation.

Read in: ja
About Ruby Modules

Overview

This article discusses Ruby modules.

What is a Module?

A mechanism for providing common methods and constants to classes and other modules.

# Module definition
module Hi
  def say_hi
    puts "Hi!"
  end
end

Unlike classes, modules cannot be instantiated. They also cannot be inherited.

Modules can define class methods and instance methods.

Class methods cannot be called from the module's include target.

module Greet
  # Class method of the module
  def self.hi
    puts "Hi!"
  end

  # Instance method of the module
  def bye
    puts "Bye!"
  end
end

Greet.hi

class Speaker
  include Greet
end

speaker = Speaker.new
speaker.bye # => Bye!
speaker.hi # => NoMethodError

Namespace

Modules can be used to create namespaces.

module University
  class Student
    def self.say
      puts "I am a student"
    end
  end
end

class Student
  def self.say
    puts "I am a student"
  end
end

Student.say # => I am a student
University::Student.say # => I am a student

Mixin

Mixins allow adding or overriding instance methods in classes without using inheritance.

While classes cannot inherit multiple times, multiple inheritance can be achieved through module mixins.

class Greet
  include Hi
end

puts Greet.new.say_hi # => Hi!

It is worth noting that while Mixins and Traits are similar, Mixins use inheritance, whereas Traits can compose methods through various means other than inheritance, giving them a slightly different nuance.

cf. ja.wikipedia.org - Mixin
cf. ja.wikipedia.org - Trait

Adding Singleton Methods to Classes Using extend

You can add singleton methods to a class using extend.

module Hi
  def hi
    puts "Hi!"
  end
end

class Greet; end

Greet.new.extend(Hi).hi # => Hi!

References

Tags: Ruby
Share: 𝕏 Post Facebook Hatena
✏️ View source / Discuss on GitHub
☕ Support

If you enjoy this blog, consider supporting it. Every bit helps keep it running!


Related Articles