Joshua Ball
4/29/2009 7:20:00 AM
I am having trouble understanding Ruby object cleanup wrt scope. In
particular, I would think that an object is getting deleted, but it
turns out that is not the case. I have an RSpec test below. The
BinarySearchTree size is defined as:
def size
@count = ObjectSpace.each_object(TreeNode) {}
end
I have the following Spec code:
describe BinarySearchTree do
it "should have size ZERO to start with" do
@tree = BinarySearchTree.new
@tree.size.should == 0
end
it "should have a size of ONE when we insert an item" do
@tree = BinarySearchTree.new
@tree.insert(5);
@tree.size.should == 1
end
it "should have a size of TWO when we insert two items" do
@tree = BinarySearchTree.new
@tree.insert(5);
@tree.insert(3);
@tree.size.should == 2
end
end
And the problem is, that when I get to the last assertion,
>> @tree.size.should == 2
It fails, saying that there are 3 objects (not 2). Presumably because
the previous BinarySearchTree didn't delete the TreeNode.
Can you explain why?
And what can I do about it? (including "don't use ObjectSpace that
way")