[lnkForumImage]
TotalShareware - Download Free Software

Confronta i prezzi di migliaia di prodotti.
Asp Forum
 Home | Login | Register | Search 


 

Forums >

comp.lang.ruby

how to dump contents of an array as parameters

akifusenet

8/22/2007 10:53:00 AM



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-....

3 Answers

Stefano Crocco

8/22/2007 10:57:00 AM

0

Alle mercoledì 22 agosto 2007, Akif Tokuz ha scritto:
> Hi
> i 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

akifusenet

8/22/2007 11:11:00 AM

0

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-....

Kaldrenon

8/22/2007 12:58:00 PM

0

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-....

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