From: matz@... (Yukihiro Matsumoto) Date: 1997-05-22T14:40:54+09:00 Subject: [ruby-list:3002] Re: access to instance variable まつもと ゆきひろです In message "[ruby-list:3001] Re: access to instance variable" on 97/05/22, toyofuku@juice.or.jp writes: | 豊福@パパイヤです。 | @tabstop = @default_tabstop の方はエラーにはならないの |ですが、このときの右辺の @default_tabstop は何を見ている |のでしょう。 メソッドと違いインスタンス変数は初期化されていなくてもエラー にならないからです.@default_tabstopはBufferのインスタンスの 初期化されないインスタンス変数(値はnil)を参照しています. | ではこれならどうだ。 | | class Buffer | @default_tabstop = 8 | def Buffer.default_tabstop() | @default_tabstop | end | def Buffer.default_tabstop=(n) | @default_tabstop = n | end ここは class Buffer class << Buffer attr :default_tabstop, TRUE end というわざがありますね. # 新しい概念を出して混乱させているような…. | バッファローカル変数っぽく書くのはこれでいいんでしょうか。 そうですね.でもこれだとBufferのサブクラスとは値が共有されま せんから,バッファローカル変数のデフォルト値を格納するテーブ ルを持つのが良いのでは. class Buffer DEFAULT_VALUES = {} DEFAULT_VALUES["tabstop"] = 8 def initialize @tabstop = DEFAULT_VALUES["tabstop"] end end あるいはバッファローカル変数をインスタンス変数で実装すること そのものを避けてしまって, class Buffer DEFAULT_PROPS = {} DEFAULT_PROPS["tabstop"] = 8 def property(name) if @property and @property.key? name @property[name] else DEFAULT_PROPS[name] end end def set_property(name, value) @property = {} unless @property @property[name] = value end end なんてのはどうでしょう. buf = Buffer.new buf.property("tabstop") buf.set_property("tabstop", 4) という感じで使うんですけど. まつもと ゆきひろ /:|)