如何在 Ruby 中要求一个块? [英] How to require a block in Ruby?

查看:41
本文介绍了如何在 Ruby 中要求一个块?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有任何内置方法要求将块传递给 Ruby 方法?我意识到如果 block_given? 为假,我可以引发异常,但有没有更好的方法来做到这一点?

Is there any built in way to require that a block be passed to a Ruby method? I realize I can just raise an exception if block_given? is false, but is there some nicer way to do it?

推荐答案

只需使用 yield.

如果在方法中包含 yield,并且 给出块,则会引发错误.

If you include yield in a method, and a block is not given, it throws an error.

把它放在一个文件中并运行它:

Put this in a file and run it:

def needs_block
    yield
end

needs_block

它会抛出这样的错误:

LocalJumpError: no block given
    from (irb):14:in `needs_block'
    from (irb):16

这篇关于如何在 Ruby 中要求一个块?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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