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.