J
Justin To
class Tree
attr_reader :value
def initialize(value)
@value = value
@children = []
end
def <<(value)
subtree = Tree.new(value)
@children << subtree
return subtree
end
end
t = Tree.new("Parent")
child1 = t << "Child 1"
child2 = t << "Child 2"
child2 << "Grandchild 2.1"
ggc1 = child1 << "Grandchild 1.1"
ggc1 << "Great Grand Child 1.1.1"
ggc2 = child1 << "Grandchild 1.2"
ggc2 << "Great Grand Child 1.2.1"
class Tree
def each
yield value
@children.each do |child_node|
child_node.each { |e| yield e } # mainly confuesd at this point
end
end
end
t.each { |x| puts x }
Hi, I'm a little confused about the algorithm used to display each item
in a tree...
at: child_node.each { |e| yield e }
when does the block { |e| yield e } come into play? Does the each method
for child_node occur first?
Thanks in advance!
attr_reader :value
def initialize(value)
@value = value
@children = []
end
def <<(value)
subtree = Tree.new(value)
@children << subtree
return subtree
end
end
t = Tree.new("Parent")
child1 = t << "Child 1"
child2 = t << "Child 2"
child2 << "Grandchild 2.1"
ggc1 = child1 << "Grandchild 1.1"
ggc1 << "Great Grand Child 1.1.1"
ggc2 = child1 << "Grandchild 1.2"
ggc2 << "Great Grand Child 1.2.1"
class Tree
def each
yield value
@children.each do |child_node|
child_node.each { |e| yield e } # mainly confuesd at this point
end
end
end
t.each { |x| puts x }
Hi, I'm a little confused about the algorithm used to display each item
in a tree...
at: child_node.each { |e| yield e }
when does the block { |e| yield e } come into play? Does the each method
for child_node occur first?
Thanks in advance!