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.
2c0a2cbea5455db466aed567de71bfd2?d=identicon&s=25 Andrew Gibson (esquilax)
on 2006-05-01 21: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
2c0a2cbea5455db466aed567de71bfd2?d=identicon&s=25 Andrew Gibson (esquilax)
on 2006-05-01 22: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?
47b1910084592eb77a032bc7d8d1a84e?d=identicon&s=25 Joel VanderWerf (Guest)
on 2006-05-03 18:58
(Received via mailing list)
Andrew Gibson 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)
4299e35bacef054df40583da2d51edea?d=identicon&s=25 James Gray (bbazzarrakk)
on 2006-05-03 18:58
(Received via mailing list)
On May 1, 2006, at 2:04 PM, Andrew Gibson 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 Gray II
D8fb06dfc08a477ecb0a76ffdbff3475?d=identicon&s=25 Chiaro Scuro (chiaroscuro)
on 2006-05-03 18:58
(Received via mailing list)
that's block.call(child), no?
This topic is locked and can not be replied to.