To your why, another why: why do you need to use multiple parallel
assignments in one statement? That said, parallel assignments are
somewhat
known to be a rather messy bit of syntax I’m apparently not as savvy
with
as I thought, since I can’t make heads or tails of what is really
happening.
My personal tip woukd be that the assignments are associative
right-to-left, and only the leftmost assignment is evaluated as a
parallel
one.
What probably happens is broken down into simpler statements:
a = a, b # a == [1, 2]
a, b = b, *a # a ==2, b==1
where the return value of the expression is the rvalue.
So the end values are what you expect, just the return value of the
expression isn’t.
Hint: it’s easy to avoid obscure syntax, so do that if possible. Noone
really admires godawful one-liners from hell in code he expects to
understand a week after writing it, even if there is a certain charm to
getting things done with them
Also, parallel assignment syntax is undergoing certain subtle, but
significant changes that seem to resolve some of the ambiguity - you
might
want to look on one of the webpages that summarize changes in Ruby 1.9.
That doesn’t seem to explain the return value [2, 1, 2] of the expression.
Why not? the return value of an assignment is the right hand
side. In this case [2, 1 , 2]. The first and last value there
coming from b, and the middle value is the return value of the
assignment a = a.
Try this:
irb(main):001:0> a, b = [1, 2, 3, 4] # sets a=1 and b=2
=> [1, 2, 3, 4]
irb(main):002:0> a, b = [1, c = 2, 3] # sets a=1, b=2, and c = 2
=> [1, 2, 3]
Ah well, for some strange reason I thought the parser would check for a
parallel assignment form inside the array constructor as well.
Apparently
not… Right, that example pretty much clears the issue up.
Ah well, for some strange reason I thought the parser would check for a
parallel assignment form inside the array constructor as well.
Apparently not… Right, that example pretty much clears the issue up.
Within method arguments, the “,” gets parsed as an argument separator
not an array separator:
Ah well, for some strange reason I thought the parser would check for a
parallel assignment form inside the array constructor as well. Apparently
not… Right, that example pretty much clears the issue up.
The thing is, if you’ve got an array [a,b], and you add to it so that
it is [a,b,c=1], the meaning of the “a,b” part doesn’t change; rather,
you’re understood to have added an element. The comma semantics are
different in these different contexts, in other words.