Skip to content

Commit e0677e7

Browse files
committed
Detach children on remove_all!
Ensure children become true roots after remove_all! by clearing their parent links. This matches the method's contract and prevents stale parent references from corrupting later traversal or metrics.
1 parent b19ee94 commit e0677e7

2 files changed

Lines changed: 14 additions & 1 deletion

File tree

lib/tree.rb

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -543,7 +543,10 @@ def remove_from_parent!
543543
# @see #remove!
544544
# @see #remove_from_parent!
545545
def remove_all!
546-
@children.each(&:remove_all!)
546+
@children.each do |child|
547+
child.remove_all!
548+
child.set_as_root!
549+
end
547550

548551
@children_hash.clear
549552
@children.clear

test/test_tree.rb

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -693,6 +693,16 @@ def test_remove_all_bang
693693

694694
assert(!@root.children?, 'Should have no children')
695695
assert_equal(1, @root.size, 'Should have one node')
696+
697+
# Removed children should be detached (root? == true).
698+
assert(@child1.root?, 'Child1 should be a root after remove_all!')
699+
assert(@child2.root?, 'Child2 should be a root after remove_all!')
700+
assert(@child3.root?, 'Child3 should be a root after remove_all!')
701+
assert(@child4.root?, 'Child4 should be a root after remove_all!')
702+
assert_nil(@child1.parent, 'Child1 parent should be nil after remove_all!')
703+
assert_nil(@child2.parent, 'Child2 parent should be nil after remove_all!')
704+
assert_nil(@child3.parent, 'Child3 parent should be nil after remove_all!')
705+
assert_nil(@child4.parent, 'Child4 parent should be nil after remove_all!')
696706
end
697707

698708
# Test the remove_from_parent! method.

0 commit comments

Comments
 (0)