有没有更好的方法来防止“屈服”?当没有传入任何块时?
我有一个产生的方法,它看起来像:
def a_method(*params)
# do something
yield
# do something else
end
如果传入一个块,我希望这个方法产生该块;如果没有传入任何块,该方法应该默默地跳过yield语句,而不会因以下内容而崩溃:
no block given (yield) (LocalJumpError)
当然,最直接的方法是将方法更改为:
def a_method(*params, &block)
# do something
yield if block
# do something else
end
但是没有更漂亮的方法吗?
I have a method that yields, which looks like:
def a_method(*params)
# do something
yield
# do something else
end
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
是的! :)
Yes! :)