Robert Klemme
1/8/2005 1:25:00 PM
"itsme213" <itsme213@hotmail.com> schrieb im Newsbeitrag
news:WkJDd.9898$ho.9719@fe2.texas.rr.com...
> Why does
> def f; 1, 2, 3; end
You sure, that this is the code you use?
>> def f; 1, 2, 3; end
SyntaxError: compile error
(irb):49: syntax error
def f; 1, 2, 3; end
^
from (irb):49
from (null):0
I'll use
>> def f; return 1, 2, 3; end
=> nil
> x,y,z = f
> give x=1, y=2, z=3
>
> While
> x = f
> gives x=[1, 2, 3]?
It's an optimization to save typing: if there are multiple values and on one
side there is only one value "*" is automatically prepended:
>> x = f
=> [1, 2, 3]
>> x
=> [1, 2, 3]
>> x = *f
=> [1, 2, 3]
>> x
=> [1, 2, 3]
If you want just the first element you got to do
>> x, = f
=> [1, 2, 3]
>> x
=> 1
> Also:
> x,y=[1, 2], 3 #=> x=[1,2] and y[3], fine
> x,y=[1, 2] #=> x=1, y=2 : not fine
>
> This is inconsistent. Instead I propose:
> x,y,z = f #=> x=1,y=2,z=3 (as current)
> x = f #=> x = 1 (CHANGE)
> *x = f #=> x=[1, 2, 3] (CHANGE)
> x, y = *f #=> an error (f on R.h.s. is not an array)
> x, y, z = [1, 2, 3], 4, 5 #=> x=[1, 2, 3], y=4, z=5 (current)
> x, y, z = [1, 2, 3] #=> x=[1, 2, 3], y=nil, z=nil (CHANGE)
> *x = [1, 2, 3] #=> x = [[1, 2, 3]] (current)
> x, y, z = *[1, 2, 3] #=> x=1, y=2, z=3 (current)
>
> I am trying to write a getter that returns the instance variable +
> something
> special if that instance variable has not been initialized. Normal calls
> would ignore the second return value. The behavior above makes it
> difficult.
> Alternatives? Will this continue in 2.0?
>
> Thanks.
>
> btw: I think arrays and multiple values should be strictly separated
> syntactic classes.
IMHO we have to judge the costs of this change (broken code, confused coders
:-)) vs. what we gain (more consistency). Dunno on what side the balance
will come down though.
Kind regards
robert