From: Ayumu Aizawa Date: 2008-12-04T18:20:17+09:00 Subject: [ruby-list:45690] Re: クラスメソッド はじめまして、相澤といいます。 派生した質問なのですが、最初の河村さんの例のようにクラスではなくクラス名の文字列から そのクラスのインスタンスを取得することもできるのでしょうか。 自分に思いつくのはevalくらいですがもうちょっとスマートな解があれば教えて下さい。 2008/12/04 18:09 : > From: Masutoyo Kawamura > Subject: [ruby-list:45688] クラスメソッド > Date: Thu, 4 Dec 2008 17:54:15 +0900 > > るびきちです。 > >> 何か良い方法はないでしょうか。 > > あります。 > >> paper = [] >> paper[1]="PaperA" >> paper[2]="PaperB" > > Rubyのクラスはオブジェクトなので文字列ではなくてクラス名そのものを指定すれば > うまくいきます。 > > paper = [] > paper[1]=PaperA > paper[2]=PaperB > > さらに、これらの行は配列リテラルを使って > paper = [nil, PaperA, PaperB] > と書けば一発です。 > > # 配列の添字は0からなのでpaper[0]はとりあえずnilを入れておきました。 > >> class PaperA < PaperCommon >> def initialize(s) >> super(s) >> end > > > サブクラスのinitializeメソッドはsuper以外の処理をしていないので不要です。 > > Rubyのインデントは慣習上2です。 > > class PaperCommon > def initialize(s) > @s=s > end > > def common_prc1 > @s = @s.upcase > end > > def common_prc3 > puts @txt > end > end > > class PaperA < PaperCommon > def differ_prc2 > @txt = "center\n" > @txt += @s > end > end > > class PaperB < PaperCommon > def differ_prc2 > @txt = "left\n" > @txt += @s > end > end > > paper = [nil, PaperA, PaperB] > > i=1 > yousi = paper[i].new("kwmr") > yousi.common_prc1 > yousi.differ_prc2 > yousi.common_prc3 > # >> center > # >> KWMR > > -- > rubikitch > Blog: http://d.hatena.ne.jp/rubikitch/ > Site: http://www.rubyist.net/~rubikitch/ > >