class WeakRef - Documentation for Ruby 4.1
Description: class WeakRef: Weak Reference class that allows a referenced object to be garbage-collected. A WeakRef may be used exactly like the object it references.
Keywords: ruby,class,WeakRef

🔍

No recent searches

# class WeakRef

Weak Reference class that allows a referenced object to be garbage-collected.

A `WeakRef` may be used exactly like the object it references.

Usage:

    foo = Object.new            # create a new object instance
    p foo.to_s                  # original's class
    foo = WeakRef.new(foo)      # reassign foo with WeakRef instance
    p foo.to_s                  # should be same class
    GC.start                    # start the garbage collector
    p foo.to_s                  # should raise exception (recycled)

### Constants

VERSION

  The version string

### Public Class Methods

new (orig)
Source

    # File lib/weakref.rb, line 35
    def initialize(orig)
      case orig
      when true, false, nil
        @delegate_sd_obj = orig
      else
        @@__map[self] = orig
      end
      super
    end

Creates a weak reference to `orig`

Calls superclass method `Delegator::new`

### Public Instance Methods

weakref_alive? ()
Source

    # File lib/weakref.rb, line 56
    def weakref_alive?
      @@__map.key?(self) or defined?(@delegate_sd_obj)
    end

Returns true if the referenced object is still alive.