Ludo wrote:
Is there a way to explicitly destroy an object [in] Ruby?
No, you need to get rid of all references to that object and then let
the garbage collector destroy.
Am I fool to want to do this ??
I wouldn’t use those words but generally speaking it’s dangerous to
destroy an object that other objects still hold references to. In C++
and other languages that use more explicit memory management these are
referred to as “dangling” pointers, and they’re the source of a lot of
debugging headaches.
I’m working on agents programation, and I try to use Ruby for this,
but I’d like to have the possibility to kill an agent,
so other agents should have to perceive the death … but if they have a
reference on the killed agent, the object is still in ObjectSpace …
OK. One solution that immediately comes to mind is some application of
the Observer pattern. When an agent is “killed”, part of its dying
process is to send a message out to any other interested agents:
class Agent
def die
@friends.each do |friend|
friend.notifyOfDeath(self)
end
end
end
For this to work, we assume that the other agents (the “friends”) have
previously registered themselves with this agent, e.g.
class Agent
def befriend(anotherAgent)
unless @friends.contains? anotherAgent
@friends << anotherAgent
end
end
end
You’ll also need to decide what should happen when an agent gets word of
another agent’s death, e.g.
class Agent
def notifyOfDeath(anAgent)
# The agent "anAgent" is on his deathbed.
# If I'm still holding any references to this agent
# I need to get rid of them now!
end
end
And so a short example of its use would go like this:
# Create some agents
bond = Agent.new
jinx = Agent.new
# Jinx wants to know when Bond dies
bond.befriend(jinx)
# Kill Bond; this should trigger a call to
# Jinx's notifyOfDeath() method.
bond.die
Hope this helps,
Lyle