Ruby optional parameters

Bruno Antunes picture Bruno Antunes · May 1, 2009 · Viewed 176.6k times · Source

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?

Answer

jshen picture jshen · May 1, 2009

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)