0
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?

【Ruby】include vs extend

Last updated at Posted at 2025-02-03

モジュールを取り込む時に使うincludeextendの違いについて理解が曖昧だったため整理。

includeとすると、インスタンスメソッドとしてモジュール内の関数が取り込まれる。
一方、extendとすると、クラスメソッドとしてモジュール内の関数が取り込まれる。

module MyModule
  def my_method
    "Hello"
  end
end

# includeの場合
class ClassA
  include MyModule
end

# extendの場合
class ClassB
  extend MyModule
end

# 使用方法の違い
ClassA.new.my_method  # includeはインスタンスメソッドとして追加
ClassB.my_method      # extendはクラスメソッドとして追加
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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?