[ruby] Ruby optional parameters

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?

This question is related to ruby optional-parameters

The answer is


You could do this with partial application, although using named variables definitely leads to more readable code. John Resig wrote a blog article in 2008 about how to do it in JavaScript: http://ejohn.org/blog/partial-functions-in-javascript/

Function.prototype.partial = function(){
  var fn = this, args = Array.prototype.slice.call(arguments);
  return function(){
    var arg = 0;
    for ( var i = 0; i < args.length && arg < arguments.length; i++ )
      if ( args[i] === undefined )
        args[i] = arguments[arg++];
    return fn.apply(this, args);
  };
};

It would probably be possible to apply the same principle in Ruby (except for the prototypal inheritance).


It is possible :) Just change definition

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

to

def ldap_get ( base_dn, filter, *param_array, attrs=nil )
scope = param_array.first || LDAP::LDAP_SCOPE_SUBTREE

scope will be now in array on its first place. When you provide 3 arguments, then you will have assigned base_dn, filter and attrs and param_array will be [] When 4 and more arguments then param_array will be [argument1, or_more, and_more]

Downside is... it is unclear solution, really ugly. This is to answer that it is possible to ommit argument in the middle of function call in ruby :)

Another thing you have to do is to rewrite default value of scope.


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)

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


Recently I found a way around this. I wanted to create a method in the array class with an optional parameter, to keep or discard elements in the array.

The way I simulated this was by passing an array as the parameter, and then checking if the value at that index was nil or not.

class Array
  def ascii_to_text(params)
    param_len = params.length
    if param_len > 3 or param_len < 2 then raise "Invalid number of arguments #{param_len} for 2 || 3." end
    bottom  = params[0]
    top     = params[1]
    keep    = params[2]
    if keep.nil? == false
      if keep == 1
        self.map{|x| if x >= bottom and x <= top then x = x.chr else x = x.to_s end}
      else
        raise "Invalid option #{keep} at argument position 3 in #{p params}, must be 1 or nil"
      end
    else
      self.map{|x| if x >= bottom and x <= top then x = x.chr end}.compact
    end
  end
end

Trying out our class method with different parameters:

array = [1, 2, 97, 98, 99]
p array.ascii_to_text([32, 126, 1]) # Convert all ASCII values of 32-126 to their chr value otherwise keep it the same (That's what the optional 1 is for)

output: ["1", "2", "a", "b", "c"]

Okay, cool that works as planned. Now let's check and see what happens if we don't pass in the the third parameter option (1) in the array.

array = [1, 2, 97, 98, 99]
p array.ascii_to_text([32, 126]) # Convert all ASCII values of 32-126 to their chr value else remove it (1 isn't a parameter option)

output: ["a", "b", "c"]

As you can see, the third option in the array has been removed, thus initiating a different section in the method and removing all ASCII values that are not in our range (32-126)

Alternatively, we could had issued the value as nil in the parameters. Which would look similar to the following code block:

def ascii_to_text(top, bottom, keep = nil)
  if keep.nil?
    self.map{|x| if x >= bottom and x <= top then x = x.chr end}.compact
  else
    self.map{|x| if x >= bottom and x <= top then x = x.chr else x = x.to_s end}
end

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"