From: shugo@... (=?ISO-2022-JP?B?GyRCQTBFRBsoQiAbJEI9JDhjGyhC?= / maeda shugo) Date: 1997-08-28T21:25:16+09:00 Subject: [ruby-list:3911] Re: class variable 前田です。 In message "[ruby-list:3902] Re: class variable" Yukihiro Matsumoto wrote: ||[その1] || クラス変数はないのですか。 | |ありません.定数を使ってエミュレートできます. | | class Foo | F = [0] | def foo | F[0] += 1 | print F[0], "\n" | end | end 前僕がした質問ですね(^^; class << Foo attr :foo, TRUE end っていう手もありますね。 class Module def class_attr(name, writable) if name.is_a? Fixnum name = name.id2name end if writable writable = "TRUE" else writable = "FALSE" end eval %{ class << self attr :#{name}, #{writable} end } end end class Foo class_attr :foo, TRUE end とか。 || class Foo || @default_x = 123 || def initialize || @x = @default_x || end || def print_x || print @x || end || end || || foo = Foo.new || foo.print_x || # なんで 123 でなくて nil になるの? 上のを使えば class Foo @default_x = 123 class_attr :default_x def initialize @x = type.default_x # 1.0なら eval(type).default_xですね。 # Foo.default_xでもいいかな。 end def print_x print @x end end とすれば期待どおりの動作になるのではないでしょうか? |# まとめられたら FAQ に追加して下さいませんか? > 前田さん 了解しました。 -- 前田 修吾