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 #this does not work
end
end
fish = Creature.new
croc = Crocodile.new
croc.eat(fish)
After the crocodile has eaten a creature and absorbed its energy, the creature should cease to exist. But the code above doesn't destroy the creature.
I know that if I say fish = nil
, the object that the varible fish
refers to will be garbage collected. But saying creature = nil
inside the Crocodile's eat
method doesn't accomplish that.
From inside croc.eat, can I say "since the variable 'fish' was passed to me, when I'm done, I'm going to set 'fish' to nil?"
I've essentially taken the approach that Chuck suggested, with some modifications. Here was my reasoning:
Therefore, I did this:
@creaturelist
. (The reason I used an instance variable and not a class variable is so that any subclass of Creature
can have its own list, too.)@creaturelist
and returns an ID to the creature.@id
variable.Creature.remove(@id)
, and the only reference to itself gets deleted.Now I can do this:
class Predator < Creature
def eat(creature)
@energy += creature.energy
creature.die
end
end
fish = Creature.new
Creature.list #shows the fish
croc = Predator.new
croc.eat(fish)
Creature.list #no more fish
Of course, in this example, fish
still points to that creature object, so it's not garbage collected. But eventually, creatures will be created and eat each other based on rules, so I won't be individually naming them.
I think the problem is that you're thinking of the program itself as the world in which these simulated things live rather than simulating one.
fish = Creature.new
croc = Crocodile.new
$world = [fish, croc]
class Crocodile
def eat(creature)
@energy += creature.energy
$world.delete creature
end
end
croc.eat fish
world # [croc], now all by his lonesome, the last creature in the world :(
And assuming the fish
variable had gone out of scope like it would in a properly structured program, that object would most likely now be garbage.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With