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
...
end
ldap_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 attrs
end
ldap_get("first_arg", "second_arg", attrs: "attr1, attr2") # => "attr1, attr2"
It isn't possible to do it the way you've defined ldap_get
. However, if you define ldap_get
like this:
def ldap_get ( base_dn, filter, attrs=nil, scope=LDAP::LDAP_SCOPE_SUBTREE )
Now you can:
ldap_get( base_dn, filter, X )
But now you have problem that you can't call it with the first two args and the last arg (the same problem as before but now the last arg is different).
The rationale for this is simple: Every argument in Ruby isn't required to have a default value, so you can't call it the way you've specified. In your case, for example, the first two arguments don't have default values.
1) You cannot overload the method (Why doesn't ruby support method overloading?) so why not write a new method altogether?
2) I solved a similar problem using the splat operator * for an array of zero or more length. Then, if I want to pass a parameter(s) I can, it is interpreted as an array, but if I want to call the method without any parameter then I don't have to pass anything. See Ruby Programming Language pages 186/187