Forum: Ruby Passing array instead of individual parameters?

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
2d239ae0bfe9bf98621956c70122f190?d=identicon&s=25 Stefan Kruger (Guest)
on 2008-11-10 15:08
(Received via mailing list)
[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
A61ecce13ed142622f24a5ca3a123922?d=identicon&s=25 Matthew Moss (Guest)
on 2008-11-10 15:14
(Received via mailing list)
On Nov 10, 2008, at 8:05 AM, Stefan Kruger wrote:

> # 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)
C40020a47c6b625af6422b5b1302abaf?d=identicon&s=25 Stefano Crocco (crocco)
on 2008-11-10 15:31
(Received via mailing list)
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
This topic is locked and can not be replied to.