Reputation: 3821
I'm learning the parallel assignment operator in Ruby now. When I tried using it to swap values in an array, I got unexpected results. Couldn't find the answer to this online and was hoping someone can shed the light on what is happening here.
First example:
array = [1,2,3]
=> [1, 2, 3]
array[0,1] = array[1,0]
=> []
array
=> [2, 3] #thought this would be = [2,1,3]
Where did array[0] go and why wouldn't Ruby swap the values?
Second example:
array = [1,2,3]
=> [1, 2, 3]
array[0,1] = [1,0]
=> [1, 0]
array
=> [1, 0, 2, 3] #was expecting [1,0,3]
Why did Ruby insert the right hand side into array and not substitute the values?
Upvotes: 1
Views: 6038
Reputation: 18803
The array[0,1]
syntax is picking a slice of the array starting at 0
and of length 1
. Longer slices make that more obvious.
> a = [1,2,3]
=> [1,2,3]
> a[0,2]
=> [1, 2]
To swap the way you want in your first example, you need to specify both indices independently.
> a[0], a[1] = a[1], a[0]
=> [2, 1]
> a
=> [2, 1, 3]
In your second example, Ruby replaces the array[0,1]
slice with [1, 0]
, effectively removing the first element and inserting the new [1, 0]
. Changing to array[0], array[1] = [1, 0]
will fix that for you too.
Upvotes: 6
Reputation: 755
Parallel assignment involves specifying multiple variables on the left-hand side of the operator - your first attempt was close, but not quite what I believe you intended to do. In order to get the behavior you expected, you'd need to write:
array[0], array[1] = array[1], array[0]
In contrast, you are writing array[0, 1]
, which effectively refers to a "slice" of the array as one object.
Upvotes: 2