Ruby初心者の友達に、moduleに関して基本的なことを教えていて、
その時の備忘録です。
module
「クラスと何が違うのか」とよく聞かれるので、まとめてみると、以下の2つ。
- インスタンスを生成することはできない
- 継承することはできない
なるなる。
で、モジュールはどういったときに使うのというと、以下の4つになります。
- 名前空間を作る
- モジュールメソッドを、クラスのインスタンスメソッドとして使う
- モジュールメソッドを、あるオブジェクトの特異メソッド(クラスメソッド)として使う
- モジュール関数を定義して使う
では、一個一個見ていきましょう。
名前空間
名前の衝突を防ぐために、使う。
下の コードのように名前の衝突を防ぎます。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
module First class Name def greet_name puts "I am first_name" end end end module Last class Name def greet_name puts "I am last_name" end end end first = First::Name.new first.greet_name |
include
moduleに定義されているメソッドをクラスのインスタンスメソッドとして取り組むことができる
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
module Name def puts_name(name) puts "I am #{name}" end end class Main include Name end m = Main.new m.puts_name "mike" => "I am mike" |
includeは、複数できる。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
module FirstName def puts_first_name(name) puts "I am #{name}" end end module LastName def puts_last_name(name) puts "I am #{name}" end end class Main include FirstName include LastName end m = Main.new m.puts_first_name "mike" m.puts_last_name "Hoge" => "I am mike" => "I am Hoge" |
extend
moduleに定義したメソッドをオブジェクトに取り組むことができる。
1 2 3 4 5 6 7 8 9 10 11 |
module Greet def greet_to(name) puts "I am #{name}" end end o = Object.new o.extend Greet o.greet_to "tomoay" => "I am tomoya" |
クラスもオブジェクトなので、クラスに取り組むこともできる。
その場合、クラスメソッドとしてmoduleに定義したメソッドを使うことができる
1 2 3 4 5 6 7 8 9 10 11 12 13 |
module Greet def greet_to(name) puts "I am #{name}" end end class Name extend Greet end name = Name.greet_to 'tomoya' => "I am tomoya" |
module関数
moduleは、関数にすることができる
1 2 3 4 5 6 7 8 9 10 |
module Greet def greet_to(name) puts "I am #{name}" end module_function :greet_to end Greet.greet_to "tomoya" => "I am tomoya" |
まとめ
実際にコードを書いてみれば、理解しやすいですね。
コメントを残す