Ruby optional parameters Ruby optional parameters ruby ruby

Ruby optional parameters


You are almost always better off using an options hash.

def ldap_get(base_dn, filter, options = {})  options[:scope] ||= LDAP::LDAP_SCOPE_SUBTREE  ...endldap_get(base_dn, filter, :attrs => X)


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)

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.


Time has moved on and since version 2 Ruby supports named parameters:

def ldap_get ( base_dn, filter, scope: "some_scope", attrs: nil )  p attrsendldap_get("first_arg", "second_arg", attrs: "attr1, attr2") # => "attr1, attr2"