是否可以声明一个以块为默认值的方法? [英] Is it possible to declare a method with block as default value?

查看:75
本文介绍了是否可以声明一个以块为默认值的方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想写一个带一个块的方法,如果没有给出块,则应该使用默认块.所以我想要这样的东西:

I want to write a method which takes a block and if no block given it should use a default block. So I want to have something like this:

def say_hello(name, &block = ->(name) { puts "Hi, #{name}" })
  # do something
end 

但是,当我尝试这样做时,出现语法错误.

But when I'm trying to do so I'm getting the syntax error.

我知道我可以使用

I know I can deal with my problem using block_given?. But I am interested in first approach. Am I missing something or this is just not possible?

推荐答案

某些答案建议使用block_given?,但是由于给出块的可能性不大,因此您可以使用nilfalse只需使用||=.

Some answers suggest using block_given?, but since there is no possibility that a block would be nil or false when it is given, you can simply use ||=.

def say_hello(name, &block)
  block ||= ->(name){puts "Hi, #{name}"}
  # do something
end

这篇关于是否可以声明一个以块为默认值的方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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