On 28.06.2010 14:52, Andy Bogdanov wrote:
> I was trying to make an iterator that goes through a simple tree
> structure something like that:
>
> class Node
> ..
> def each_child(&block)
>    @children.each { |child| yield(child) { child.each_child(&block) } }
> end
> ..
> end
>
> so i could generate a simple html menu:
>
> puts "<ul>"
> root_node.each_child { |node|
>    puts "<li><a href=\"#{child.link}\">#{child.title}</a></li>"
>    unless node.children.empty?
>      puts "<ul>"
>      yield
>      puts "</ul>"
>    end
> }
> puts "</ul>"
>
> But it turns out that Ruby syntax prohibits passing blocks to yield. A
> simple workaround is to use block.call instead of yield everywhere.
>
> Is there any good reason for that limitation?

There is no point in passing a block to yield because yield implicitly 
calls the block passed to the current method.

I think what you really want is this:

def each_child(&b)
   b[self] # or b.call(self) or simply yield self
   @children.each {|ch| ch.each_child(&b)}
   self
end

Kind regards

	robert

-- 
remember.guy do |as, often| as.you_can - without end
http://blog.rubybestpractices.com/