没有块传递时,是否有更好的方法来防止“屈服"? [英] Are there better ways to prevent 'yield' when no block is passed in?

查看:63
本文介绍了没有块传递时,是否有更好的方法来防止“屈服"?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个产生的方法,看起来像:

I have a method that yields, which looks like:

def a_method(*params)
  # do something
  yield
  # do something else
end

如果要传入一个块,我希望此方法产生该块;并且如果没有传入任何块,则该方法应轻率地跳过yield sentense,而不会崩溃,例如:

I want this method to yield the block if a block is passed in; and if no block is passed in, the method should sliently skip the yield sentense without crashing with something like:

 no block given (yield) (LocalJumpError)

当然,最直接的方法是将方法更改为:

Of course, the most straightforward way is changing the method to:

def a_method(*params, &block)
  # do something
  yield if block
  # do something else
end

但是没有更漂亮的方法吗?

But aren't there prettier ways?

推荐答案

是的! :)

def a_method(*params)
  # ...
  yield if block_given?
  # ...
end

这篇关于没有块传递时,是否有更好的方法来防止“屈服"?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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