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?
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.