LoginSignup
0
0

More than 3 years have passed since last update.

Ruby モジュールとは?

Posted at

モジュールとは?

モジュールとは、処理を1つにまとめたものである。

# 例:足し算、引き算の処理をまとめたCaluculateモジュール
module Calculate
  def add(a, b)
    a + b
  end

  def sub(a, b)
    a - b
  end
end

モジュールとクラスの違い

モジュールとクラスは似ているが、以下のような違いがある。

  • モジュールはインスタンスを作れない
  • モジュールは継承できない
  • クラスは処理とデータを持つが、モジュールは処理だけを持つ

モジュールの用途

モジュールは以下のような用途で使用される。

名前空間の提供

同じクラスでも別の名前のモジュールの中に入れることで別のクラスとして使用することができる。

# 例:同じImageクラスを別のモジュールに含めて違うクラス(User::ImageとPost::Image)として扱う
module User
  class Image
    def self.hoge
      puts 'user image'
    end
  end
end

module Post
  class Image
    def self.hoge
      puts 'post image'
    end
  end
end

User::Image.hoge #=> "user image"
Post::Image.hoge #=> "post image"

クラスにインスタンスメソッドとして取り込む

includeメソッドを使用してモジュールの処理を対象のクラスのインスタンスメソッドとして取り込む事ができる。

# 例:UserモジュールをImageクラスのインスタンスメソッドとして取り込む

module User
  def hoge
    puts 'user image'
  end
end

class Image
  include User
end

image = Image.new
image.hoge #=> "user image"

クラスにクラスメソッドとして取り込む

extendメソッドを使用してモジュールの処理を対象のクラスのクラスメソッドとして取り込む事ができる。

# 例:UserモジュールをImageクラスのクラスメソッドとして取り込む

module User
  def hoge
    puts 'user image'
  end
end

class Image
  extend User
end

Image.hoge #=> "user image"

まとめ

  • モジュールは処理をまとめたもの
  • モジュールはクラスと違い、インスタンスの作成や継承はできない
  • 名前空間の提供や、インスタンスメソッド・クラスメソッドとしてクラスに取り込むことができる
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0