[英]Ruby: Yielding from a method that takes arguments?
I've written a very simple, recursive, tree-traversal method in ruby. 我用ruby编写了一个非常简单的递归树遍历方法。 I want to yield the results of this traversal so that I can easily iterate through the nodes of the tree. 我想得出此遍历的结果,以便可以轻松地遍历树的节点。
def bottom_up_traversal (node)
if(node.has_leaf_children?)
node.children.each{|i| yield i}
else
node.children.each{|i| bottom_up_traversal(i)}
yield node
end
end
And when I attempt to call it, like: 当我尝试调用它时,例如:
bottom_up_traversal(@root){|this_node| puts this_node }
I get a 'Wrong number of arguments (0 for 1)'. 我收到“参数数量错误(0为1)”。 I know this is probably just something silly i'm doing with syntax, but I cannot find any (even basic) examples of this being done....which leads me to believe that I'm misunderstanding how I should be using code-bocks (something which is admittedly new to me) 我知道这可能只是我在使用语法时所做的愚蠢的事情,但是我找不到完成此操作的任何(甚至是基本的)示例。...这使我相信我误解了我应该如何使用代码, cks(对我来说是新事物)
So, could you perhaps tell me how I'm supposed to call this method, or where I've gone wrong? 因此,您也许可以告诉我应该如何调用此方法,或者我哪里出错了?
In your method when you call bottom_up_traversal(i)
you aren't passing the original block when you invoke it the first time. 在您的方法中,当您调用bottom_up_traversal(i)
时,您在第一次调用它时并没有传递原始块。 Untested, but I think you want something more like this: 未经测试,但我认为您想要更多类似这样的东西:
def bottom_up_traversal (node, &block)
if(node.has_leaf_children?)
node.children.each{|i| yield i}
else
node.children.each{|i| bottom_up_traversal(i, &block)}
end
end
###
bottom_up_traversal(@root){|this_node| puts this_node }
In the end it wasn't the original method call, but the way the method recursively calls itself that was the issue, which stemmed not from me not really understanding how code-blocks work it seems. 最后,这不是最初的方法调用,而是方法递归调用自身的方式才是问题所在,这并不是我不真正理解代码块的工作原理引起的。
Phillip's answer with extra 'yield self' calls worked perfectly. 菲利普(Phillip)的额外“屈服自我”电话很完美。
Thank you very much! 非常感谢你!
def bottom_up_traversal (node, &block)
if(node.has_leaf_children?)
node.children.each{|i| yield i}
yield node
else
node.children.each{|i| bottom_up_traversal(i, &block)}
yield node
end
end
called like 叫像
bottom_up_traversal(@root){|this_node| puts this_node }
traverses them in perfect order. 以完美的顺序遍历它们。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.