クラス
インスタンス(オブジェクト)を生成する設計図
モジュール
インスタンスは生成できないが、機能(メソッドや定数)をまとめるためのもの
クラス
クラスはインスタンスを生成でき、インスタンスごとに状態を持つことができる。
initializeを定義することで、インスタンス生成時にインスタンス変数という状態を持つことができる。そして、それをインスタンスメソッドで操作することができる。
class Book
def initialize(title, author)
@title = title
@author = author
end
def description
"Title: #{@title}, Author: #{@author}"
end
end
# インスタンスを作成
book = Book.new("The Catcher in the Rye", "J.D. Salinger")
puts book.description # => "Title: The Catcher in the Rye, Author: J.D. Salinger"
モジュール
一方、モジュールはインスタンスを生成できない。
モジュールは、名前空間を提供し、メソッドや定数をまとめるために使用される。
状態(モジュール自身が持つ唯一の状態)を持つことも可能。
module BookUtils
def self.format_title(title)
title.upcase
end
def self.format_author(author)
author.capitalize
end
end
# モジュールのメソッドを呼び出す
puts BookUtils.format_title("the catcher in the rye") # => "THE CATCHER IN THE RYE"
puts BookUtils.format_author("j.d. salinger") # => "J.d. Salinger"