DEV Community

Cover image for About Ruby Modules
Kenta Takeuchi
Kenta Takeuchi

Posted on • Originally published at bmf-tech.com

About Ruby Modules

This article was originally published on bmf-tech.com.

Overview

Writing about Ruby Modules.

What is a Module

A mechanism to provide common methods and constants to classes and other modules.

# Module definition
module Hi
  def say_hi
    puts "Hi!"
  end
end
Enter fullscreen mode Exit fullscreen mode

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 where the module is included.

module Greet
  # Module class method
  def self.hi
    puts "Hi!"
  end

  # Module instance method
  def bye
    puts "Bye!"
  end
end

Greet.hi

class Speaker
  include Greet
end

speaker = Speaker.new
speaker.bye # => Bye!
speaker.hi # => NoMethodError
Enter fullscreen mode Exit fullscreen mode

Namespace

Can be used to provide a namespace.

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

class Student
  def self.say
    puts "私は学生です"
  end
end

Student.say # => 私は学生です
University::Student.say # => I am a student

Enter fullscreen mode Exit fullscreen mode

Mixin

Allows adding or overriding instance methods in a class without using inheritance.

While classes cannot have multiple inheritance, multiple inheritance can be achieved through Module Mixin.


class Greet
  include Hi
end

puts Greet.new.say_hi # => Hi!
Enter fullscreen mode Exit fullscreen mode

Incidentally, Mixin and Trait are similar, but Mixin uses inheritance, whereas Trait can compose methods through various means other than inheritance, with slightly different nuances.

cf. ja.wikipedia.org - Mixin
cf. ja.wikipedia.org - トレイト

Adding Singleton Methods to a Class Using extend

Using extend, you can add singleton methods to a class.

module Hi
  def hi
    puts "Hi!"
  end
end

class Greet; end

Greet.new.extend(Hi).hi # => Hi!
Enter fullscreen mode Exit fullscreen mode

References

Top comments (0)