Robert Klemme
12/1/2004 8:24:00 AM
"David A. Black" <dblack@wobblini.net> schrieb im Newsbeitrag
news:Pine.LNX.4.44.0411301028320.4191-100000@wobblini...
> Hi --
>
> On Wed, 1 Dec 2004, Robert Klemme wrote:
>
> >
> > "Brian Schröder" <ruby@brian-schroeder.de> schrieb im Newsbeitrag
> > news:20041130174018.40e55108@black.wg...
> > > Hello Group,
> > >
> > > I just noticed the following behaviour:
> > >
> > > $ irb --prompt-mode xmp
> > > *[:x]
> > > SyntaxError: compile error
> > > (irb):1: syntax error
> > > from (irb):1
> > > a=*[:x]
> > > ==>:x
> > >
> > > and wondered why it is the case. I always understood the * operator
as
> > pack/unpack array operator. So I would have expected the following
> > behaviour.
> > >
> > > *[:x] => :x
> >
> > No, it does not pack / unpack an array. You can only use it in a
> > situation where there is an assignment. The star indicates, that a
given
> > value should be enumerated and assigned to lvalues in order (this
applies
> > also to method argument lists).
>
> It doesn't have to be an assignment; you can do:
>
> irb(main):003:0> [1,2,*[3,4]]
> => [1, 2, 3, 4]
Thanks David! I didn't think of this case. I wonder whether this can be
viewed as an anonymous assignment.
> or:
>
> irb(main):004:0> arr = [1,2,3,4]
> => [1, 2, 3, 4]
> irb(main):005:0> Hash[*arr]
> => {1=>2, 3=>4}
That's a method argument list.
> I like to think of it as the unarr?ay (unary/unarray) operator :-)
IMHO it's not an operator, as it has mainly compile time effects, i.e., it
controls which values are assigned to which variables (in an assignment).
Note also, that the star can appear on the left side of an assignment, too
(or in the argument list of a method definition, which is basically the
same):
>> a,b,c = %w{aaa bbb ccc ddd}
=> ["aaa", "bbb", "ccc", "ddd"]
>> a
=> "aaa"
>> b
=> "bbb"
>> c
=> "ccc"
>> a,b,*c = %w{aaa bbb ccc ddd}
=> ["aaa", "bbb", "ccc", "ddd"]
>> a
=> "aaa"
>> b
=> "bbb"
>> c
=> ["ccc", "ddd"]
Kind regards
robert