From: matz@... (Yukihiro Matsumoto) Date: 1997-12-15T17:07:22+09:00 Subject: [ruby-dev:1094] Re: [Req] object refference まつもと ゆきひろです In message "[ruby-dev:1091] Re: [Req] object refference" on 97/12/15, Yukihiro Matsumoto writes: |まつもと ゆきひろです |finalizerを使えばできますね.ということはRubyレベルで書ける? とりあえず以下のようなのはいかがでしょう. 委譲用のクラスDelegaterを使ってます. -- weakref.rb # Weak Reference class that does not bother GCing. # # Usage: # foo = Object.new # foo = WeakRef.new(foo) # ... # ObjectSpace.garbage_collect # ... # foo.hash # => Raises WeakRef::RefError (because original GC'ed) require "delegate" class WeakRef Object class Delegater def initialize(obj) @obj = obj end def __getobj__ @obj end def method_missing(mid, *args) __getobj__.send mid, *args end DELEGATING_METHODS = [ "nil?", "==", "===", "=~", "eql?", "hash", "type", "clone", "dup", "to_a", "to_s", "inspect", "methods", "singleton_methods", "private_methods", "instance_variables", "remove_instance_variable", "instance_of?", "kind_of?", "is_a?" ] for method in DELEGATING_METHODS eval "def #{method}(*args); __getobj__.send :#{method}, *args; end" end end