On 25 Mar 2006, at 02:09, firstname.lastname@example.org wrote:
does the asterisk do to the array ? Any hints
on where I can find a description in the
There’s something about it near the beginning, in the section about
passing arguments to functions. In fact, until the post below, I had
no idea it could be used more generally!
The * is a “unary unarray” operator. It “un-arrays” the array into a
list of separate values.
Thus, for example:
a = [4,5,6]
[1,2,3,*a] => [1,2,3,4,5,6]
There are rules about where and when and how it can be used, but
that’s basically what’s happening when you see that.
That makes a lot of sense, thank you! Usually this will be used to
allow a function to take additional arguments:
def a_function( required_argument, also_required,
You can also use it to split out an array in to seperate parameters
(so kind of the opposite of the above). Again, this is often used
when calling a method:
As an example of both of these uses; I’d like to have an object
delegate any method calls that it can’t handle to some other object.
I could write it like this:
# Pick method calls I can’t handle, and pass them on to the delegatee.
def method_missing( method_name, *all_the_parameters )
@my_delegatee.send( method_name, *all_the_parameters )
However, the above doesn’t pick up any optional block that’s
passed to the method. To rectify that, you would probably write the
method above like this:
def method_missing( method_name, *all_the_parameters, &optional_block )
@my_delegatee.send( method_name, *all_the_parameters, &optional_block )
I think this is also discussed in the same section of the pickaxe.