how to dump contents of an array as parameters

A

Akif Tokuz

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,
 
S

Stefano Crocco

Alle mercoled=C3=AC 22 agosto 2007, Akif Tokuz ha scritto:
Hi
=C4=B1 am a beginner Rubyist and I have a small problem.


Track=3DStruct.new:)name,:surname)

#This works perfectly
tempTrack=3DTrack.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=3D[15,"b"]
tempTrack=3DTrack.new(incomingArray)
p tempTrack.name
p tempTrack.surname

Thanks.
Akif,

You need to do this:

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

I hope this helps

Stefano
 
K

Kaldrenon

Stefano said:
You need to do this:
Track.new(*[15, 'b'])
I hope this helps

Thank you Stefano. It worked.

Akif,

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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
474,264
Messages
2,571,316
Members
48,001
Latest member
Wesley9486

Latest Threads

Top