On Tue, Oct 26, 2010 at 5:21 PM, Colin Bartlett <colinb2r / googlemail.com> wrote:
> On Tue, Oct 26, 2010 at 3:05 PM, Maurizio Cirilli <mauricirl / gmail.com>wrote:
>
>> Thanks a lot Robert for your clear explanation and help.
>> In order to fully understand the code you provided, could you
>> please to tell what is the role of the asterisk in the
>> statement:
>>
>> a, b, c = *ss
>>
>> I did not find (or probably I just missed) this operator in the Ruby
>> docs I have.
>> Btw, bioinformatics libraries to Ruby community are provided by
>> the BioRuby project guys.
>>
>
> There's an explanation of *array in the online Programming Ruby, probably in
> the sections on assignment and/or method calls: I did think about searching
> for it, but the link below looks as though it has a reasonable explanation.
> Subject to correction by anyone more knowledgeable than me, the second
> statement below (extracted from the linked page) also applies to assignment,
> so you can do something like:
> aa = [1, 2]
> bb = [4, 5]
> cc = [7, 8]
> a, b, c, d, e, f, g = *aa, 3, bb, 6, *cc
> which sets a to 1, b to 2, c to 3, d to [4, 5], e to 6, f to 7, g to 8.
>
> As w_a_x_man pointed out, if the right hand side of an assignment statement
> is an array, and there are two or more variables on the left hand side of
> the assignment statement, then Ruby automatically expands the array for you,
> so you can omit the "*" operator if you want to..

It even works with one variable to the left - but then you need a comma:

09:11:30 ~$ ruby19 -e 'a=%w{foo bar baz};b,=a;p b'
"foo"

While splat alone does not work in this case:

09:11:50 ~$ ruby19 -e 'a=%w{foo bar baz};b=*a;p b'
["foo", "bar", "baz"]

You need to add the comma here as well

09:12:24 ~$ ruby19 -e 'a=%w{foo bar baz};b,=*a;p b'
"foo"

Of course, you could also do

09:12:50 ~$ ruby19 -e 'a=%w{foo bar baz};b=a.first;p b'
"foo"
09:13:18 ~$ ruby19 -e 'a=%w{foo bar baz};b=a[0];p b'
"foo"

Or, if destruction is allowed:

09:13:23 ~$ ruby19 -e 'a=%w{foo bar baz};b=a.shift;p b'
"foo"

> http://en.wikibooks.org/wiki/Ruby_Programming/Syntax/Method_Calls
> ...
> Variable Length Argument List, Asterisk Operator
>
> The last parameter of a method may be preceded by an asterisk(*), which is
> sometimes called the 'splat' operator. This indicates that more parameters
> may be passed to the function. Those parameters are collected up and an
> array is created.
> ...

Actually this is not correct any more for 1.9.*: here the splat
operator can occur at _any_ position and Ruby will do the pattern
matching for you:

09:13:29 ~$ ruby19 -e 'def f(a,*b,c) p a, b, c end;f(1,2,3,4,5)'
1
[2, 3, 4]
5
09:15:03 ~$ ruby19 -e 'def f(*a,b,c) p a, b, c end;f(1,2,3,4,5)'
[1, 2, 3]
4
5
09:15:42 ~$ ruby19 -e 'def f(a,b,*c) p a, b, c end;f(1,2,3,4,5)'
1
2
[3, 4, 5]

Kind regards

robert

-- 
remember.guy do |as, often| as.you_can - without end
http://blog.rubybestpractices.com/