Ruby - n 叉树的每个递归
已修复:请参阅编辑编辑
我在为 n 叉树编写自己的递归每个时遇到麻烦。 @element
是节点的值,@children
是所有相连的下层节点的数组。这是我的方法:
def each
yield(@element)
@children.each { |x|
x.each { |i| yield i}
}
self
end
问题是它重复了较低的元素。例如,如果我用它来打印一个值为 o 和一个子 c 的节点,它将打印“occ”而不是“oc”。我真的不知道发生了什么,所以我尝试的所有修复都无效。有什么想法吗?
编辑:我认为这可能是因为除了产生它之外,它还以某种方式调用节点值上的每个值,因此当它是单个字符的字符串时,它将产生该字符,然后使用 .each
打电话。
编辑编辑:感谢大家的阅读,但我搞砸了。问题不在于这个方法,而在于同一个类中的另一个方法,to_s。 to_s 将正确打印,但如果父节点是字符串,则更改父节点的值。每当我测试时,我总是先使用to_s,甚至没有意识到。对此感到抱歉。 (不能让我回答我自己的问题,因为我是新手)。
Fixed: See EDIT EDIT
I have trouble with writing my own recursive each for an n-ary tree. @element
is the value of the node, and @children
is an array of all connected lower nodes. This is my method:
def each
yield(@element)
@children.each { |x|
x.each { |i| yield i}
}
self
end
The problem is that it repeats the lower elements. For example, if I use this to print a node with value o and one child c, it will print 'occ' instead of 'oc'. I really don't know what's going on, so all of my attempted fixes have been ineffective. Any ideas?
EDIT: I think this could be because it's somehow calling each on the node value in addition to yielding it, so when it's a string of a single character it will yield that character then yield it again with a .each
call.
EDIT EDIT: Thanks for reading, everybody, but I messed up. The problem wasn't in this method, but in another in the same class, to_s. to_s would print correctly, but change the value of the parent node if it was a string. Whenever I tested, I always used to_s first and didn't even realize it. Sorry about this. (Can't let me answer my own question, as I'm a newbie).
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
从您的回复来看,在我看来您想要的是这样的:
一个注意事项是,由于您似乎想递归地传递 proc 对象,因此您最好将其作为
&pr 的参数
而不是使用yield
。Judging from your response, it seems to me that what you want is something like this:
One notice is that, since you seem to want to pass the proc object recursively, you should better get that as an argument as
&pr
rather than usingyield
.