I have a function that take a variable number of arguments, like this:
def myfun(*args)
# ...
end
All args are of the same type (Symbol
), so right now I document the function like if there were only one argument, saying it can take more than one, e.g.:
# this function doesn’t do anything
# @param [Symbol]: this argument does something, you can add more symbols
# if you want
def myfun(*args)
# ...
end
Is there a built-in way to handle this case?
To call a function with a variable number of arguments, simply specify any number of arguments in the function call. An example is the printf function from the C run-time library. The function call must include one argument for each type name declared in the parameter list or the list of argument types.
To use a variable number of arguments to function, use the arguments object.
You can use *args as a non-keyword argument. You will then be able to pass any number of arguments. As you can see, Python will unpack the arguments as a single tuple with all the arguments.
A variable-length argument is specified by three periods or dots(…). This syntax tells the compiler that fun( ) can be called with zero or more arguments.
The following makes sense because args
is an Array
inside the method, although none of the params are an Array
as such:
# this function doesn’t do anything
#
# @param [Array<Symbol>] args these arguments do something
# @return [nil]
def myfun(*args)
# ...
end
Note the *
is dropped from the param name in the comment. This is just to be consistent - args
is an Array
, but *args
is not.
A quick search shows quite a few projects using this style, including inside Yard's own .rb files (e.g. see source for initialize in Verifier class) - although no examples of this convention are given in the guide.
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