From: "Marvin Gülker" Date: 2009-07-23T18:41:14+09:00 Subject: Re: Ruby "star".... what's it? Mirko Viviani schrieb: > Sorry, > Complete code was like this > x, *xs = *myarray > > after executing, x is 1 and xs [2,3,4,5,6,6] ..... :o > > 2009/7/23 Max Williams > > >> Mirko Viviani wrote: >> >>> Hi everybody. >>> What means this snippet of code? Why use the "star" ? >>> >>> myarray = [1,2,3,4,5,6,6] >>> qa = *myarray >>> >>> Thank you. >>> >> In this example it doesn't really do anything, i think. Normally you >> would use the * in an argument list, in a method definition, to >> effectively say 'pull all arguments after this into a single array', eg >> >> >>>> def foo(mainarg, *otherargs) >>>> puts mainarg.inspect >>>> puts otherargs.inspect >>>> end >>>> >> => nil >> >>>> foo(1,2,3,4,5,6) >>>> >> 1 >> [2, 3, 4, 5, 6] >> => nil >> >> In this sense it's like * in a regular expression, meaning 'any number >> of arguments'. That's how i understand it anyway, a more precise >> description will probably be forthcoming :) >> -- >> Posted via http://www.ruby-forum.com/. >> >> >> > > > irb(main):001:0> x = 0 => 0 irb(main):002:0> xs = [0, 0] => [0, 0] irb(main):003:0> myarray = [1, 2, 3] => [1, 2, 3] irb(main):004:0> x, *xs = *myarray => [1, 2, 3] irb(main):005:0> x => 1 irb(main):006:0> xs => [2, 3] irb(main):007:0> x = 0 => 0 irb(main):008:0> xs = [0, 0] => [0, 0] irb(main):009:0> x, xs = myarray => [1, 2, 3] irb(main):010:0> x => 1 irb(main):011:0> xs => 2 The * is also called the "splat operator". It is used to split up an array in is parts or the other way round (like in the method definition already posted). You could also do things like: def foo(x, y) puts x puts y end ary = [1, 2] foo(ary) #=> ArgumentError foo(*ary) #=> 1, 2 Marvin