Ruby Function with Unlimited Number of Parameters
-
22-08-2019 - |
Question
How do I create a Ruby function that does not have an explicit number of parameters?
More clarification needed?
Solution
Use *rest
. here's a nice little tutorial.
OTHER TIPS
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
(If I could add a comment to the accepted answer, I would, but I don't have enough points.)
Warning: Be careful about doing this for methods processing general data. It's a great piece of syntax sugar, but there are limits to the number of arguments you can pass to a method before you get a SystemStackError. I've hit that limit using redis.mapped_mget *keys
. Also, the limit will change depending on where you use the splat operator. For instance, running pry locally, I can splat arrays of over 130,000 elements to a method. Running within a Celluloid actor, though, that limit can be less than 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 some nice examples rolling and unrolling your parameters using "*"