Ruby FAQ: How do I create a variable length argument list in a Ruby method?
One thing I really dig about Ruby is that I can create methods and functions that support variable-length argument lists. It's not something you need all the time, but it sure is nice to have it when you need it.
Here's how you create and then call a Ruby function/method that can take a variable number of arguments:
# define it def variable_args(arg1, *more) puts more end # call it variable_args(1,2,3,4)
after which the output looks like this:
2 3 4
Notice that the "1" that I use for my first function input parameter gets assigned to my first function argument, arg1
, and therefore does not appear in the output.
Very cool, isn't it? I love testing stuff like this with irb, the interactive ruby shell.
I used this Ruby varargs capability recently when processing a CSV or Excel with Ruby, and when I find that code I'll be glad to publish it here as well.