[lnkForumImage]
TotalShareware - Download Free Software

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


 

Forums >

comp.lang.ruby

Expanding array as function arguments

Witold Rugowski

12/5/2007 12:43:00 PM

Hi!
I wonder if it is possible to expand array as function arguments. Like

def foo( a, b, c)
end

foo [1,2,3].to_args


Is possible to do it?


--
Witold Rugowski
http://... (EN blog)
http://Friends...
--
Posted via http://www.ruby-....

5 Answers

Sergio Gil Pérez de la Manga

12/5/2007 12:55:00 PM

0

On Dec 5, 2007 1:43 PM, Witold Rugowski <rugowski@nhw.pl> wrote:
> Hi!
> I wonder if it is possible to expand array as function arguments. Like
>
> def foo( a, b, c)
> end
>
> foo [1,2,3].to_args
>
>
> Is possible to do it?

foo *[1,2,3]

(
similar to grouping several arguments into an array if method definition:

def foo(*args)
end

foo 1, 2, 3
)

--=20
Sergio Gil P=E9rez de la Manga
e-mail > sgilperez@gmail.com
blog > http://www.lacoctelera....

Robert Klemme

12/5/2007 12:57:00 PM

0

2007/12/5, Witold Rugowski <rugowski@nhw.pl>:
> Hi!
> I wonder if it is possible to expand array as function arguments. Like
>
> def foo( a, b, c)
> end
>
> foo [1,2,3].to_args
>
>
> Is possible to do it?

foo *[1,2,3]

robert

--
use.inject do |as, often| as.you_can - without end

Rimantas Liubertas

12/5/2007 12:57:00 PM

0

> Hi!
> I wonder if it is possible to expand array as function arguments. Like
>
> def foo( a, b, c)
> end
>
> foo [1,2,3].to_args
> Is possible to do it?

How about foo *[1, 2, 3] ? (Note the "*" -"splat").


--
Regards,
Rimantas
--
http://rim...

Witold Rugowski

12/5/2007 1:14:00 PM

0

Sergio Gil Pérez de la Manga wrote:
> foo *[1,2,3]
>
> (
> similar to grouping several arguments into an array if method
> definition:
>
> def foo(*args)
> end
>
> foo 1, 2, 3
> )

Thnx a lot ;)
--
Posted via http://www.ruby-....

MonkeeSage

12/5/2007 2:46:00 PM

0

On Dec 5, 7:13 am, Witold Rugowski <rugow...@nhw.pl> wrote:
> Sergio Gil Pérez de la Manga wrote:
>
> > foo *[1,2,3]
>
> > (
> > similar to grouping several arguments into an array if method
> > definition:
>
> > def foo(*args)
> > end
>
> > foo 1, 2, 3
> > )
>
> Thnx a lot ;)
> --
> Posted viahttp://www.ruby-....

A note on splat; it can be used to both gather and unpack elements,
depending on the context. For example...

def baz(a, b, c)
p a, b, c
end
def foo(*bar) # gathering - bar = [1, 2, 3]
baz(*bar) # unpacking - bar = 1, 2, 3
end
foo(1, 2, 3)

Regards,
Jordan