require 'weakref'
class Player
### define some accessors
def follower=(f)
@follower = WeakRef.new(f)
end
def follower
return false if @follower == nil
if @follower.weakref_alive?
@follower
else
false
end
end
end
### create 2 players
p = Player.new
p2 = Player.new
### p2 referenced as the follower of p1
p.follower = p2
### p2 is no longer valid
p2 = nil
ObjectSpace.garbage_collect
### p.follower returns false instead of the follower.
puts p.follower
So you may have came across a problem where you wanted to use references but didn't want to be responsible for having to unlink all the references if the object was removed from the Object Space. (Because the object wouldn't be removed from the Object Space until these references are all removed.)
An easy solution to this problem is a Weak Reference. These act as normal references in Ruby, however, as expected their existence won't prevent the garbage collector from doing its job. So when using weak references you simply check if they are still valid before accessing them. (If they aren't you have to handle that.) Using a weak reference after their dereferenced object has left the Object Space will result in an exception, which can also be rescued pretty easily.