Expanding an array to function args

Hello, I’m curious if there’s a way to expand an array into an argument
list given to a method in one easy step. The following contrived example
shows what I’m looking to do:

def sum(a, b)
a+b
end

args = [1,2]
sum(args) # need a way to expand args to be arguments a and b.

I fully understand that an array is a single object and that’s why
the above code would fail(missing second argument), but I’m wondering
if there’s a simple way to achieve what I’m looking for.

Thanks,
Travis Whitton whitton@atlantic.net

···


Bill Gates is a mean and selfish man and Microsoft reflects his inner poverty.

Hi,

In your example you can simply use the “*” when calling the function,
which will expand the array into its components:

sum(*args)

Regards,

Bill

···

============================================================================
Travis Whitton whitton@atlantic.net wrote:

Hello, I’m curious if there’s a way to expand an array into an argument
list given to a method in one easy step. The following contrived example
shows what I’m looking to do:

def sum(a, b)
a+b
end

args = [1,2]
sum(args) # need a way to expand args to be arguments a and b.

I fully understand that an array is a single object and that’s why
the above code would fail(missing second argument), but I’m wondering
if there’s a simple way to achieve what I’m looking for.

Thanks,
Travis Whitton whitton@atlantic.net

Bill Gates is a mean and selfish man and Microsoft reflects his inner poverty.

Yes there is, placing a * ahead of the array expands the arguments,
sum(*args)

···

On Thu, Sep 26, 2002 at 03:23:23AM +0900, Travis Whitton wrote:

args = [1,2]
sum(args) # need a way to expand args to be arguments a and b.

I fully understand that an array is a single object and that’s why
the above code would fail(missing second argument), but I’m wondering
if there’s a simple way to achieve what I’m looking for.


Alan Chen
Digikata LLC
http://digikata.com