1

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?

Petr Gazarov
  • 3,602
  • 2
  • 20
  • 37
  • First check what `array[1,0]` does alone -- returns `[]` http://ruby-doc.org/core-2.2.0/Array.html#method-i-5B-5D You are using the `Array[start, length]` notation, so the premise of swapping elements with that notation is incorrect. – Michael Berkowski Jul 10 '15 at 16:09

2 Answers2

5

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.

Kristján
  • 18,165
  • 5
  • 50
  • 62
2

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.

Sculper
  • 756
  • 2
  • 12
  • 24