Array into list of arguments - nicest way?

M

Max Williams

hey all

I want to pass the contents of an array to a method, to be interpreted
as a standard list of arguments. What's the simplest and nicest way of
doing this? (i can think of a few dirty hack ways but don't want to use
them)

eg

#have
arr = [arg1, arg2, arg3]
#want
a_method(arg1, arg2, arg3)
 
J

Jesús Gabriel y Galán

hey all

I want to pass the contents of an array to a method, to be interpreted
as a standard list of arguments. What's the simplest and nicest way of
doing this? (i can think of a few dirty hack ways but don't want to use
them)

eg

#have
arr = [arg1, arg2, arg3]
#want
a_method(arg1, arg2, arg3)

Look for documentation, etc for the splat operator (there's plenty out there):

a_method (*arr)

Jesus.
 
T

Tim Hunter

Max said:
hey all

I want to pass the contents of an array to a method, to be interpreted
as a standard list of arguments. What's the simplest and nicest way of
doing this? (i can think of a few dirty hack ways but don't want to use
them)

eg

#have
arr = [arg1, arg2, arg3]
#want
a_method(arg1, arg2, arg3)

Look up the splat operator, a.k.a. unary unarray:

a_method(*arr)
 
M

Max Williams

aha, that makes sense...

thanks a lot, everyone. I've used the splat before at the end of
parameter lists, eg

def a_method(a_thing, *args)

But i guess i didn't really properly understand what it does. I can't
find an explaanation in pickaxe, although it's not the simplest thing to
look for in the index (there's no listing for 'splat' and a lot of
listings for '*').
 
B

Brian Candler

Max said:
But i guess i didn't really properly understand what it does. I can't
find an explaanation in pickaxe, although it's not the simplest thing to
look for in the index (there's no listing for 'splat' and a lot of
listings for '*').

http://www.ruby-doc.org/docs/ProgrammingRuby/

Click on the chapter "More about Methods"

Scroll down to the section headed "Expanding Arrays in Method Calls"

It could be indexed better :)
 

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
473,995
Messages
2,570,236
Members
46,825
Latest member
VernonQuy6

Latest Threads

Top