Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby method with maximum number of parameters

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?

like image 701
Nikita Barsukov Avatar asked Feb 11 '11 10:02

Nikita Barsukov


People also ask

What is * args in Ruby?

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).

What is splat operator in Ruby?

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 parameter in Ruby?

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.


1 Answers

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 
like image 167
Simone Carletti Avatar answered Oct 11 '22 14:10

Simone Carletti