From: Nicholas Wright Date: 2006-08-26T05:00:06+09:00 Subject: Re: What does *var mean? Chih-Chao Lam wrote: > Apologies for a newbie ruby question: > > I know an asterisk can precede a parameter in the argument list of a > method definition as in > > def varargs(arg1, *rest) > > But looking at the source code of Hpricot, I see that you can precede > an asterisk before any variable. Is there a formal definition for the > use of this operator? > > irb(main):001:0> *d = 3 > => [3] > irb(main):002:0> d > => [3] > irb(main):003:0> d == [*d] > => true > irb(main):004:0> *d > SyntaxError: compile error > (irb):4: parse error, unexpected '\n', expecting '=' > from (irb):4 > > Thanks, > chao * has a few different uses. When used like this: def sum(*args) args.inject(0) {|sum, i| sum + i} end sum(1, 23, 324, 3, 4543, 938, 9128, 42, 2134) it's used to mean 'collect all passed arguments into an array'. When used like this: numbers = [1, 32, 32423, 32419879, 32517, 98172, 23478932] sum(*numbers) It means 'expand this list'. Which, in the above situation would actually pass each number to sum as an individual argument, rather than a single argument that is an array. It has a few other usages, but they are all essentially variations on the above two. - Nick