In Ruby, can one object destroy another?
For example:
class Creature def initialize @energy = 1 end attr_accessor :energy end class Crocodile < Creature def eat(creature) @energy += creature.energy creature = nil
After the crocodile ate the creature and absorbed its energy, the creature should cease to exist. But the above code does not destroy the creature.
I know that if I say fish = nil , the object referenced by varible fish will be garbage collected. But saying creature = nil inside the eat crocodile method fails.
Another way to put it
From inside croc.eat, can I say "since the variable" fish "was passed to me, when I finished, am I going to set the" fish "to zero?"
Update: issue resolved
I essentially took the approach that Chuck suggested with some changes. Here are my thoughts:
- If there is no longer any variable pointing to the object, this will be garbage collection
- If when creating an object, I add it to the hash (for example, "x" => the object) and do not create any other variable for it, and then remove this element from the hash results when garbage collecting the object
- It seems logical that a list of all creatures should be stored in a creature class
So I did this:
- In an object of the Creature class, I created a hash and assigned it to an instance variable. We will call him
@creaturelist . (The reason I used the instance variable rather than the class variable, so any subclass of Creature can also have its own list.) - In the Initialize method, the new creature passes itself to the creature class
- The creature class adds a link to this creature at
@creaturelist and returns the identifier of the creature. - The creature remembers this identifier in its own
@id variable. - If the creature dies, it calls the parent class with
Creature.remove(@id) , and only the reference to itself is deleted.
Now I can do it:
class Predator < Creature def eat(creature) @energy += creature.energy creature.die end end fish = Creature.new Creature.list
Of course, in this example, fish still points to this creature object, so it does not collect garbage. But ultimately, the creatures will be created and eat each other on the basis of the rules, so I will not individually name them.
garbage-collection ruby
Nathan long
source share