M
Matthias Luedtke
Hello Rubyists,
at first I must say that after reading this newsgroups for some weeks
now I'm happy to learn from so many smart and kind people in here. This
is the place where you actually believe that programming is fun.
I'm implementing a red black tree and I'd like to let users of the class
be able to traverse it by calling each. I managed to implement the class
so far but I am unsure whether I use the right technique to pass the
incoming block from each to the helper method traverse_inorder.
I cut the code down to the minimum, @root is of class Node which looks
like it's supposed to be
class RBTree
# Visits each node in inorder
def each(&block)
traverse_inorder(@root){|x| block.call(x)}
end
private
def traverse_inorder(x, &block)
if not x.nil? then
traverse_inorder(x.left){ |n| block.call(n) }
yield x.key
traverse_inorder(x.right){ |n| block.call(n) }
end
end
end
t = RBTree.new
t.each{ |node| puts node }
Invoking the call method explicitely on the block seems rather odd to
me. Is it the only way?
Regards,
Matthias
at first I must say that after reading this newsgroups for some weeks
now I'm happy to learn from so many smart and kind people in here. This
is the place where you actually believe that programming is fun.
I'm implementing a red black tree and I'd like to let users of the class
be able to traverse it by calling each. I managed to implement the class
so far but I am unsure whether I use the right technique to pass the
incoming block from each to the helper method traverse_inorder.
I cut the code down to the minimum, @root is of class Node which looks
like it's supposed to be
class RBTree
# Visits each node in inorder
def each(&block)
traverse_inorder(@root){|x| block.call(x)}
end
private
def traverse_inorder(x, &block)
if not x.nil? then
traverse_inorder(x.left){ |n| block.call(n) }
yield x.key
traverse_inorder(x.right){ |n| block.call(n) }
end
end
end
t = RBTree.new
t.each{ |node| puts node }
Invoking the call method explicitely on the block seems rather odd to
me. Is it the only way?
Regards,
Matthias