[ACCEPTED]-Ruby Function with Unlimited Number of Parameters-variadic-functions
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(',')
end
foo(1,2,3,4,5,6,7,8,9)
# prints:
# 1
# 2
# 3
# 4,5,6,7,8,9
0
(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.
Here's another article on the subject:
www.misuse.org/science/2008/01/30/passing-multiple-arguments-in-ruby-is-your-friend
Gives 2 some nice examples rolling and unrolling 1 your parameters using "*"
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
end
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
We use cookies to improve the performance of the site. By staying on our site, you agree to the terms of use of cookies.