[lnkForumImage]
TotalShareware - Download Free Software

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


 

Forums >

comp.lang.ruby

Passing array instead of individual parameters?

Stefan Kruger

11/10/2008 2:06:00 PM

[New to this fine language, from a Perl background]

I expected (wrongly) the following to work -

def myroutine(one, two, three)
puts "first: #{one} second: #{two} third: #{three}"
end

myroutine('brave', 'new', 'world') # as expected

# The unexpected (to me)

myparamlist = ['brave', 'new', 'world']

myroutine(myparamlist) # fails

So, my question is - is there a way of calling a routine expecting N
parameters with a list containing N elements instead?

Specifically, using the dbi module, I expected to be able to say:

sth.prepare("insert into foo (one, two, three) values (?, ?, ?)")
sth.execute(my_list_of_three_values)

but instead I need to loop through the list and bind each one in turn?

Many thanks,

stefan

--
Stefan Kruger <stefan.kruger@gmail.com>

2 Answers

Matthew Moss

11/10/2008 2:11:00 PM

0


On Nov 10, 2008, at 8:05 AM, Stefan Kruger wrote:

> [New to this fine language, from a Perl background]
>
> I expected (wrongly) the following to work -
>
> def myroutine(one, two, three)
> puts "first: #{one} second: #{two} third: #{three}"
> end
>
> myroutine('brave', 'new', 'world') # as expected
>
> # The unexpected (to me)
>
> myparamlist = ['brave', 'new', 'world']
>
> myroutine(myparamlist) # fails
>
> So, my question is - is there a way of calling a routine expecting N
> parameters with a list containing N elements instead?


myroutine(*myparamlist)



Stefano Crocco

11/10/2008 2:29:00 PM

0

Alle Monday 10 November 2008, Stefan Kruger ha scritto:
> myroutine(myparamlist) # fails
>
> So, my question is - is there a way of calling a routine expecting N
> parameters with a list containing N elements instead?

myroutine(*myparamlist)

The *, when put in front of an array in an argument list transforms each
element of the array in an argument to the method. It is sometimes called the
"splat operator", even if it's not a true operator.

Stefano