[ACCEPTED]-Ruby Function with Unlimited Number of Parameters-variadic-functions

Accepted answer
Score: 32

Use the splat operator *

def foo(a,b,c,*others)
   # this function has at least three arguments,
   # but might have more
   puts a
   puts b
   puts c
   puts others.join(',')
# prints:
# 1
# 2
# 3
# 4,5,6,7,8,9


Score: 21

Use *rest. here's a nice little tutorial.


Score: 6

(If I could add a comment to the accepted 13 answer, I would, but I don't have enough 12 points.)

Warning: Be careful about doing 11 this for methods processing general data. It's 10 a great piece of syntax sugar, but there 9 are limits to the number of arguments you can 8 pass to a method before you get a SystemStackError. I've 7 hit that limit using redis.mapped_mget *keys. Also, the limit will 6 change depending on where you use the splat 5 operator. For instance, running pry locally, I 4 can splat arrays of over 130,000 elements 3 to a method. Running within a Celluloid 2 actor, though, that limit can be less than 1 16,000 elements.

Score: 2

Here's another article on the subject:


Gives 2 some nice examples rolling and unrolling 1 your parameters using "*"

Score: 0

In addition, here is also an interesting 10 "look-alike" technique to passing multiple 9 named parameters. It's based on the fact that 8 Ruby will convert a list of named parameters 7 to a hash if given in a place where one 6 positional parameter is expected:

def hashed_args_test(args = {})
  p args

hashed_args_test(arg1: "val1", arg2: "val2")
# => {:arg1=>"val1", :arg2=>"val2"}

hashed_args_test( {arg1: "val1", arg2: "val2"} )
# => {:arg1=>"val1", :arg2=>"val2"}

So both 5 ways of invoking the method supply a hash 4 of (any number of) elements – whether using 3 the hash syntax explicitly or something 2 that looks exactly like passing named parameters. (Tested 1 with Ruby 2.5.3.)

More Related questions