125

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?

7 Answers 7

137

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)
2
  • 23
    A common strategy is to have a default options hash and merge in whatever was passed in: options = default_options.merge(options) Commented Dec 13, 2012 at 10:50
  • 7
    I discourage this because the options don't tell you what the method expects or what the default values are Commented Jan 17, 2015 at 21:30
131

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.

9
  • 22
    A little gotcha with this method: e.g. If you're trying to make the default value for scope true and you pass in false, scope ||= true won't work. It evaluates the same as nil and will set it to true Commented Nov 10, 2011 at 5:32
  • 4
    is it possible with the current version of ruby, 3 years after this answer?
    – dalloliogm
    Commented Jun 3, 2012 at 16:10
  • 1
    @JoshPinter, nice explanation. Basically ||= is not a = b or c, I cringed at seeing xyz||=true. It's saying if it's nil, it's always true. If it's true, it's true.
    – Damon Aw
    Commented Oct 23, 2012 at 9:24
  • 7
    With everyone saying how bad scope ||= true is, I'm surprised that no one has mentioned that the better way to do this is with scope = LDAP::LDAP_SCOPE_SUBTREE if scope.nil?. Of course, even that is assuming that nil is an invalid value. Commented May 29, 2013 at 6:00
  • 1
    Update to this oldie: An alternative is to use the underscore notation. Unfortunately, it has the same effect as setting the parameter to nil. Some may like the notation: ldap_get(base_dn, filter, _, X) (note: I do not know (yet) when this was introduced in Ruby. Interesting SO thread). Commented Mar 6, 2014 at 4:02
54

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"
1
3

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.

0
1

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

0

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
-1

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.

4
  • 4
    This solutions is completely wrong. It is a syntax error to use a default value parameter (attrs=nil) after a splat (*param_array). Commented May 29, 2013 at 6:08
  • 3
    -1: Erik is correct. Causes a syntax error in irb 2.0.0p247. According to The Ruby Programming Language, in Ruby 1.8 the splat parameter had to be last except for an &parameter, but in Ruby 1.9 it could be followed by "ordinary parameters" as well. In neither case was a parameter with a default legal after a parameter with a splat.
    – andyg0808
    Commented Sep 19, 2013 at 0:31
  • Ruby Programming Language page 186/187 the splat is fine to use with methods. It has to be the last parameter in the method unless & is used.
    – rupweb
    Commented Mar 12, 2014 at 12:01
  • So AndyG is right, the order needs to be: def ldap_get ( base_dn, filter, attrs=nil, *param_array)
    – rupweb
    Commented Mar 12, 2014 at 12:08

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.