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 valuedef 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.
NoArgument
as default valueclass 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
.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With