How to dump contents of an array as parameters

Hi
ı am a beginner Rubyist and I have a small problem.

Track=Struct.new(:name,:surname)

#This works perfectly
tempTrack=Track.new(15,"b")
p tempTrack.name
p tempTrack.surname

But I want to create a temptrack with an incoming array how can i
convert

[15,"b"] in to 15,"b"

#And of course this doesnt work
incomingArray=[15,"b"]
tempTrack=Track.new(incomingArray)
p tempTrack.name
p tempTrack.surname

Thanks.
Akif,

···

--
Posted via http://www.ruby-forum.com/.

Alle mercoledì 22 agosto 2007, Akif Tokuz ha scritto:

Hi
ı am a beginner Rubyist and I have a small problem.

Track=Struct.new(:name,:surname)

#This works perfectly
tempTrack=Track.new(15,"b")
p tempTrack.name
p tempTrack.surname

But I want to create a temptrack with an incoming array how can i
convert

[15,"b"] in to 15,"b"

#And of course this doesnt work
incomingArray=[15,"b"]
tempTrack=Track.new(incomingArray)
p tempTrack.name
p tempTrack.surname

Thanks.
Akif,

You need to do this:

Track.new(*[15, 'b'])

I hope this helps

Stefano

Stefano Crocco wrote:

You need to do this:

Track.new(*[15, 'b'])

I hope this helps

Stefano

Thank you Stefano. It worked.

Akif,

···

--
Posted via http://www.ruby-forum.com/\.

Just to expand (pun?) the concept:

the * operator, when applied to method arguments, work two ways, if I
understand correctly:

In a method call, putting * before an array breaks it apart into its
elements and passes them as individual arguments to a method. So
  x.do_stuff(a,b,c,)
is equivalent to
  x.do_stuff(*[a,b,c])
or
  y = [a,b,c]
  x.do_stuff(*y)

In a method declaration, * can be used to collect an undetermined
number of arguments into an array. Suppose that you have a method that
accepts optional arguments, and depending on the options there could
be 1, 2, or 3 values passed in. One way (there are others) to handle
that would be to make the method look like this:

def do_stuff(*args)
  if args.length > 2
    puts "optional stuff"
  else
    puts "default stuff"
  end
end

I believe I've gotten this right, but I'm something of a Nuby myself.
Any comments or corrections of my explanation would be greatly
appreciated.

HTH,
Andrew

···

On Aug 22, 7:11 am, Akif Tokuz <akifuse...@gmail.com> wrote:

Stefano Crocco wrote:
> You need to do this:

> Track.new(*[15, 'b'])

> I hope this helps

> Stefano

Thank you Stefano. It worked.

Akif,
--
Posted viahttp://www.ruby-forum.com/.