Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to decide whether an optional argument was given or not in a ruby method

I have a method with an optional argument. How can I decide whether the Argument was given or not?

I came up with the following solutions. I am asking this question since I am not entirely satisfied with any of them. Exists there a better one?

nil as default value

def m(a= nil)
    if a.nil?
        ...
    end
end

The drawback with this one is, that it cannot be decided whether no argument or nil was given.

custom NoArgument as default value

class NoArgument
end

def m(a= NoArgument.new)
    if NoArgument === a
        ...
    end
end

Whether nil was given can be decided, but the same problem exists for instances of NoArgument.

Evaluating the size of an ellipsis

def m(*a)
    raise ArgumentError if m.size > 1
    if m.size == 1
        ...
    end
end

In this variant it can be always decided whether the optional argument was given. However the Proc#arity of this method has changed from 1 to -1 (not true, see the comment). It still has the disadvantage of beeing worse to document and needing to manually raise the ArgumentError.

like image 594
johannes Avatar asked Jan 02 '12 21:01

johannes


1 Answers

Jorg W Mittag has the following code snippet that can do what you want:

def foo(bar = (bar_set = true; :baz))
  if bar_set
    # optional argument was supplied
  end
end
like image 146
Andrew Grimm Avatar answered Nov 07 '22 04:11

Andrew Grimm