LoginSignup
0
0

More than 5 years have passed since last update.

【Ruby】コーディングメモ(モジュール)

Posted at

環境

ruby 2.4.1p111

モジュールとは

  • クラスとは異なり、オブジェクトの生成、継承が行えない。
  • しかしながら、1つのクラスからは1つのスーパークラスしか継承できない為、複数クラスにまたがるような共通メソッドを定義する場合、モジュールクラスに定義することで、効率的に共通メソッドを定義できる利点がモジュールに有る。
  • 書き方は以下
module モジュール名
 処理
end
  • 例として、以下サンプルを書きました。CommonFuncの名のモジュール、Employeeというスーパークラス、Tanakaという派生クラスを定義し、main.rbから呼び出しています。
  • 拙記事「【Ruby】コーディングメモ(モジュール)」のサンプル(employee.rb、tanaka.rb、main.rb)を一部修正して流用しています。
commonFunc.rb
module CommonFunc
  def sayYes
    puts "Yes"
  end
end
employee.rb
class Employee
  include CommonFunc
  attr_accessor :name
  def initialize(name)
    @name = name
  end

  def sayName
    puts "My Name is " + @name
  end
end
tanaka.rb
class Tanaka < Employee
  def doing
    puts "I'm working."
  end
end
main.rb
load "commonFunc.rb"
load "employee.rb"
load "tanaka.rb"

tanaka = Tanaka.new("Ichiro Tanaka");
tanaka.sayYes
  • 結果は以下です。
Yes
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