クラス、メソッド

目次

クラス、メソッド

メソッドは

def メソッド名
    #引数なしメソッド
    ・・・
end

def メソッド名(引数1、引数2)
    #引数ありメソッド
    ・・・
end

のように定義する。
メソッドの最後で評価された式を戻り値として返す。
呼び出し側の引数に*(アスタリスク)をつけるとその配列が展開される。

BBSを例に作ってみよう。
タイトル、名前、本文を要素にもつArticleというクラスを作ると次のようになる

class Article
    def initialize( title, name, comment )
        @title = title
        @name = name
        @comment = comment
    end
end

ここで定義したinitializeメソッドはデフォルトコンストラクタnewの内部で呼ばれるようです。
引数にはデフォルト値を与えることができる。
各要素を引数にとり、インスタンス変数に代入している。

次にto_sを作ってみる。現在はこんな感じ。

article = Article.new( "無題", "たすく", "本文" )
print article.to_s ⇒ #<Article:0x402d36ac>

Rubyのクラスは閉じられていないので、次のようにメソッドを追加することができる。

class Article
    def to_s
        [@title, @name, @comment].join("\t")
    end
end
article = Article.new( "無題", "たすく", "本文" )
print article.to_s ⇒ 無題 たすく 本文

ここで、[A,B,C]というのはA,B,Cを要素にもつ配列であり、
joinメソッドは引数で渡された文字列で配列の要素を連結した文字列を返す。

アクセサメソッド

インスタンス変数を参照できるようにしてみよう。

class Article
    #参照メソッド
    def title
        @title
    end
    #代入メソッド
    def title=( a_title )
        @title = a_title
    end
end

と、いちいち全てについて書くのは面倒くさい。
attrを使うと次のように書ける。

class Article
    #参照メソッド
    attr_reader :title, :name, :comment
    #代入メソッド
    attr_writer :title, :name, :comment
end
article = Article.new( "無題", "たすく", "本文" )
print article.comment ⇒ 本文
article.comment = "変更できます。"
print article.comment ⇒ 変更できます。

クラス変数

このarticleに識別用の記事IDを付けよう。
クラス変数@@idはクラス共通の変数なので、これを使用する。
initializeを書き換えてみよう。

class Article
    @@id = Array.new()
    attr_reader :id
    def initialize( id, title, name, comment )
        if id
            if @@id.include?(id)
                raise ArgumentError, "id exists"
            else
                @id = id
                @@id.push(id)
            end
        else
            case @@id.size
            when 0
                @id = 0
            when 1
                @id = @@id[0] + 1
            else
                @id = @@id.sort!.last + 1
            end
            @@id.push(@id)
        end
        @title = title
        @name = name
        @comment = comment
    end
end
article = Article.new( nil, "無題","たすく","本文" )
article2 = Article.new( nil, "無題","たすく","本文" )
print article.id ⇒ 0
print article2.id ⇒ 1

ここで初めて?ifendcasewhenendが出てきた。
また、Arrayクラスも初めて出てきたが、ここでは詳しい説明はしない。おおよそメソッド名のとおりである。
すでにIDが存在したときはraiseで例外を発生させている。

記事IDの追加に伴いto_sメソッドも以下のようになる。

class Article
    def to_s
        [@id, @title, @name, @comment].join("\t")
    end
end

クラスメソッド

クラスには特定のオブジェクトに関連つけられないメソッドが必要になることがある。
File.delete( ファイル名 )などがそうで、これをクラスメソッドと呼ぶ。
ちなみにnewもクラスメソッドである。

データファイルから読み込む場合のコンストラクタがあると便利である。

line = "2\t無題\tたすく\t本文\n"
id, title, name, comment = line.chomp.split(/\t/)
article = Article.new( id.to_i, title, name, comment )
print article.to_s ⇒ 2 無題 たすく 本文

なんてやるのは面倒なので、クラスメソッドArticle.from_sを作りその内部でnewするのである。

class Article
    def Article.from_s( line )
        (id, title, name, comment) = line.chomp.split(/\t/)
        Article.new( id.to_i, title, name, comment )
    end
end
line = "3\t無題\tたすく\t本文\n"
article = Article.from_s( line )
print article.to_s ⇒ 3 無題 たすく 本文

完成版

以上よりArticleは以下のようになる。

class Article
    @@id = Array.new()
    #参照メソッド
    attr_reader :id, :title, :name, :comment
    #代入メソッド
    attr_writer :title, :name, :comment
    def initialize( id, title, name, comment )
        if id
            if @@id.include?(id)
                raise "id exists"
            else
                @id = id
                @@id.push(id)
            end
        else
            case @@id.size
            when 0
                @id = 0
            when 1
                @id = @@id[0] + 1
            else
                @id = @@id.sort!.last + 1
            end
            @@id.push(@id)
        end
        @title = title
        @name = name
        @comment = comment
    end
    def to_s
        [@id, @title, @name, @comment].join("\t")
    end
    def Article.from_s( line )
        (id, title, name, comment) = line.chomp.split(/\t/)
        Article.new( id.to_i, title, name, comment )
    end
end

スポンサード リンク

トラックバック

トラックバックURL
https://linux-life.net/tb/program/ruby/doc/chapter04/
Linux Life 〜 No linux, No life 〜
プログラミング > Ruby > Ruby入門 > クラス、メソッド