I have a method, that should accept maximum 2 arguments. Its code is like this:
def method (*args) if args.length < 3 then puts args.collect else puts "Enter correct number of arguments" end end
Is there more elegant way to specify it?
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).
Splat operator or start (*) arguments in Ruby define they way they are received to a variable. Single splat operator can be used to receive arguments as an array to a variable or destructure an array into arguments. Double splat operator can be used to destructure a hash.
What is a parameter? Parameters in ruby are variables that are defined in method definition and which represent the ability of a method to accept arguments. So, if we will not have the appropriate parameters, then we will not be able to pass arguments to a method that will contain the data we need.
You have several alternatives, depending on how much you want the method to be verbose and strict.
# force max 2 args def foo(*args) raise ArgumentError, "Too many arguments" if args.length > 2 end # silently ignore other args def foo(*args) one, two = *args # use local vars one and two end # let the interpreter do its job def foo(one, two) end # let the interpreter do its job # with defaults def foo(one, two = "default") 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