Ruby可选参数 [英] Ruby optional parameters

查看:86
本文介绍了Ruby可选参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我定义这样的Ruby函数:

If I define a Ruby functions like this:

def ldap_get ( base_dn, filter, scope=LDAP::LDAP_SCOPE_SUBTREE, attrs=nil )

我怎么称呼它仅提供前两个和最后一个参数?为什么不是这样的

How can I call it supplying only the first 2 and the last args? Why isn't something like

ldap_get( base_dn, filter, , X)

可能,或者如果可能,怎么办?

possible or if it is possible, how can it be done?

推荐答案

当前红宝石无法实现.您不能将空"属性传递给方法.您可以获得的最接近的结果是传递nil:

This isn't possible with ruby currently. You can't pass 'empty' attributes to methods. The closest you can get is to pass nil:

ldap_get(base_dn, filter, nil, X)

但是,这会将范围设置为nil,而不是LDAP :: LDAP_SCOPE_SUBTREE.

However, this will set the scope to nil, not LDAP::LDAP_SCOPE_SUBTREE.

您可以做的是在方法中设置默认值:

What you can do is set the default value within your method:

def ldap_get(base_dn, filter, scope = nil, attrs = nil)
  scope ||= LDAP::LDAP_SCOPE_SUBTREE
  ... do something ...
end

现在,如果您按上述方式调用方法,则行为将与您预期的一样.

Now if you call the method as above, the behaviour will be as you expect.

这篇关于Ruby可选参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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