From: 7stud -- Date: 2008-02-20T18:53:23+09:00 Subject: Re: What does *args do? Philip Brocoum wrote: > I sometimes see funcs declared with def fun (blah, *args) > > What does the *args do? Thanks! Normally, if you define a method with two parameter variables, for instance: def show(x, y) #x, y are parameter variables puts x puts y end show(1, 2) --output:-- 1 2 ...then you *must* call the method with two arguments(1 and 2 are the arguments). Otherwise you get an error, for example: show(1, 2, 3) --output:-- 'show': wrong number of arguments (3 for 2) (ArgumentError) The * allows you to call a method and specify more arguments: def show(x, *arr) puts x arr.each do |elmt| puts elmt end end show(1, 2, 3) puts show(1, 2, 3, 4) --output:-- 1 2 3 1 2 3 4 You still need to call show() with at least one argument so that ruby can assign the first argument to the x parameter variable, but after that you can specify any number of arguments in the method call. The extra arguments are gathered up into an array and then assigned to the variable name after the *, in this case that would be: arr. If you have a method call like the following: show(1, 2, 3, 4) #def show(x, *arr) ruby assigns the argument 1 to the parameter variable x, and then ruby creates an array to hold 2, 3, 4: [2, 3, 4] and then ruby assigns that array to the parameter variable arr: arr = [2, 3, 4] In effect the * in this definition: def show(x, *arr) says to ruby, "Please assign the first argument in the method call to x, then gather up any additional arguments, stick them into an array, and assign the array to the variable name to my right. -- Posted via http://www.ruby-forum.com/.