For example, if I have
def function(arg)
#do stuff
end
how do I only allow arg
to be an Array? I could do
def function(arg)
if arg.class != 'Array'
return 'Error'
else
#do stuff
end
end
but is there any better way of doing this?
In the code you posted, *args simply indicates that the method accepts a variable number of arguments in an array called args . It could have been called anything you want (following the Ruby naming rules, of course).
We can explicitly accept a block in a method by adding it as an argument using an ampersand parameter (usually called &block ). Since the block is now explicit, we can use the #call method directly on the resulting object instead of relying on yield .
Note the difference between parameters and arguments: Function parameters are the names listed in the function's definition. Function arguments are the real values passed to the function. Parameters are initialized to the values of the arguments supplied.
You can't do def function(Array arg)
like in other languages, but you can replace four lines of your second snippet by a single one:
def function(arg)
raise TypeError unless arg.is_a? Array
# code...
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