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?

More than 5 years have passed since last update.

moduleとmixin

Last updated at Posted at 2019-10-04

モジュール

module SampleModule
  CONST_NUM =100

  def const_num
    CONST_NUM
  end
end

puts SampleModule::CONST_NUM

# moduleをincludeしたあとならモジュール名を省略して定数に直接アクセスできるようになる
include SampleModule
puts CONST_NUM
puts const_num

module_functionを使うことでmodule名に.をつけてメソッドを呼び出せるようになる

module SampleModule
  def module_function_sum(a, b)
    a + b
  end

  module_function :module_function_sum
end

SampleModule.module_function_sum(1, 100)
=> 101

ミックスイン

モジュールの機能をクラスに取り込むには
  include モジュール名
とする

module SampleModule
  def sum(a, b)
    a + b
  end
end

class Sample
  include SampleModule

  def class_sum(a, b)
    sum(a, b)
  end
end

実行してみる

sample = Sample.new
puts sample.sum(1, 100)
=> 101

puts sample.class_sum(1, 100)
=> 101

使い道

  • 複数のクラスで使う共通のメソッドをmoduleとして定義し、適宜includeして使う
  • 特定のメソッドをmoduleとしてまとめておきユーティリティーとして使用する
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?