Forum: Ruby traversal of a tree + block code

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
Andrew G. (Guest)
on 2006-05-01 23:04
Hi:

I want to be able to traverse a tree and for each node perform some
random code...sounds like an ideal situation for blocks, right? :)

My problem is that I'm not sure how to keep passing the code block in
the recursive call.  This is my best attempt so far... i'm not very
strong in this area so any advice would be welcome! :)

  def self.depthFirstTraversal(parent , &block)
    children = parent.children
    children.each do |child|
      block.call(child)
      self.depthFirstTraversal(child) do |node|
        block.call(node)
      end
    end
  end
Andrew G. (Guest)
on 2006-05-02 00:05
Ahhh..found my solution:

  def self.depthFirstTraversal(parent , &block)
    children = parent.children
    children.each do |child|
      block[child]
      self.depthFirstTraversal(child, &block)
    end
  end

I'm not familiar with the [] for passing the argument to the proc(?) ...
anyone have any comments?
Joel VanderWerf (Guest)
on 2006-05-03 20:58
(Received via mailing list)
Andrew G. wrote:
>     children = parent.children
>     children.each do |child|
>       block.call(child)

Instead of...

>       self.depthFirstTraversal(child) do |node|
>         block.call(node)
>       end

try this...

        depthFirstTraversal(child, &block)
James G. (Guest)
on 2006-05-03 20:58
(Received via mailing list)
On May 1, 2006, at 2:04 PM, Andrew G. wrote:

>     children = parent.children
>     children.each do |child|
>       block.call(child)
>       self.depthFirstTraversal(child) do |node|

depthFirstTraversal(child, &block)

>         block.call(node)
>       end

Lose these two lines.

>     end
>   end

Just FYI, Ruby naming conventions are to use methods_like_this,
notLikeThisJavaStyle.  ;)

James Edward G. II
Chiaro S. (Guest)
on 2006-05-03 20:58
(Received via mailing list)
that's block.call(child), no?
This topic is locked and can not be replied to.