产量递归
所以我想做这样的事情:
def func(x,y)
if x.length == 1 then
n = x.pop()
yield(n,y)
else
n = x.pop()
yield(n,func(x,y))
end
end
这样称呼它:
a = func([1,2,3,4,5],0) do |x,y|
x+y
end
是否可以做这样的事情?我一直没有收到任何块(yield)(LocalJumpError)。
我什至尝试做一些不同的事情:
def func(x,y)
func(x,y) do |tail|
..
end
end
但没有运气,
谢谢。
So i am trying to do something like this:
def func(x,y)
if x.length == 1 then
n = x.pop()
yield(n,y)
else
n = x.pop()
yield(n,func(x,y))
end
end
calling it like:
a = func([1,2,3,4,5],0) do |x,y|
x+y
end
Is it possible to do something like this? I keep getting no block given (yield) (LocalJumpError).
I even tried doing something a little different:
def func(x,y)
func(x,y) do |tail|
..
end
end
but no luck
Thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
是的,您可以显式地将块作为参数:
您仍然可以使用yield关键字让出它,但您也可以在递归时传递它:
两种情况下的
&
都意味着< code>block 参数不是普通参数,而是表示可以附加到任何 Ruby 方法调用的块。Yes, you can take the block as an argument explicitly:
You can still yield to it with the yield keyword, but you can also pass it as you recurse:
The
&
in both cases means that theblock
argument is not a normal argument, but represents the block that can be attached to any Ruby method call.您缺少在递归调用中传递块。
递归调用应该如下所示:-
由于您错过了在递归调用中传递块,因此当代码命中时:-
在递归调用中,方法 func 没有作为参数传递的块,但 ruby 尝试调用一个不存在的块,因此出现错误。
You are missing to pass the block in the recursive call.
The recursive call should be like as below:-
Since you missed to pass the block in the recursive call, when the code hits:-
the method func doesn't have block passed as argument,in the recursive call, but ruby tries to call a non-existent block and hence the error.