我可以评估Proc中的一个块吗? [英] Can I evaluate a block inside a Proc?

查看:89
本文介绍了我可以评估Proc中的一个块吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我可以在Proc内产生一个块吗?考虑以下示例:

Can I yield a block inside a Proc? Consider this example:

a = Proc.new do
  yield
end

a.call do
  puts "x"
end

我想要实现的是打印x,但是用ruby 2.0解释这一点会提高LocalJumpError: no block given (yield).

What I'm trying to achieve is to print x, but interpreting this with ruby 2.0 raises LocalJumpError: no block given (yield).

推荐答案

不能,因为您创建的Proc是独立的yield-也就是说,它是一个yield,其中没有块它的上下文.尽管您可以使用指定的参数调用proc,从而将参数传递给proc,但是yield不能基于指定的参数工作;它执行在proc的闭包中找到的块.并且proc的关闭是预定义的;它不会被修改,只是因为您稍后使用一个块来调用它.

No you can't, because the Proc you've created is an independent yield - that is, it's a yield that has no block in its context. Although you can call procs with specified parameters and thereby pass the parameters into the proc, yield doesn't work based on specified parameters; it executes the block found within the proc's closure. And the proc's closure is predefined; it is not modified just because you call it later with a block.

因此,这等同于直接在irb中键入"yield"(不在任何方法定义中),这将返回LocalJumpError: no block given (yield)错误.

So it's equivalent of just typing 'yield' straight into irb (not within any method definitions) which returns the LocalJumpError: no block given (yield) error.

这篇关于我可以评估Proc中的一个块吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆