LoginSignup
0
2

More than 5 years have passed since last update.

[Ruby][初心者] モジュールとミックスイン

Last updated at Posted at 2018-08-18

モジュール

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.call_sum(1, 100)
=> 101

使い道

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