1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

Rubyのmoduleとは?

Posted at

moduleとは

クラスと似ており、変数やメソッドを定義することができます。
ただし、クラスのようにインスタンスは生成できませんし、継承もできません。

・moduleでインスタンスを作ろうとした場合
moduleでインスタンスは作成できないため、エラーとなります。

module Test
  def hoge
    put "hoge"
  end
end

tester = Test.new

#  エラーメッセージ
undefined method `new' for Test:Module (NoMethodError)

・moduleを継承して新しいmoduleを作成することは出来ないのでエラーとなります。

module Test
  def hoge
    "hoge"
  end
end

module Test2 < Test
end

# エラーメッセージ
syntax error, unexpected '<'

moduleを使うメリット

上記のようにclassと違って融通の効かない感じがありますが、moduleを使うことで以下のようなメリットがあります。

・多重継承ができる
Rubyは単一継承しか出来ません。しかし、moduleを用いることで多重継承に似た機能を実装できます。
以下のようにincludeしてmoduleを追加することをミックスインと言います。

module Test
  def hoge
    puts "Testmoduleが呼び出されている"
  end
end

class User
  # Test moduleを読み込んでいる
  include Test

  def get_user
    # Testモジュールをincludeしているので、hogeメソッドが使える
    hoge()
    puts "get_userが呼び出されている"
  end
end

# Userインスタンスの作成
user = User.new
# Userクラスのget_userメソッドを呼び出す。
# Userクラスで、Testモジュールをincludeしているので、hogeメソッドが使える
user.get_user
1
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
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?