arraysruby

How to move an element of an array to the beginning of the array


I want to move the element at index 2 to the start of the array [1, 2, 3, 4], the resulting array should look like [3, 1, 2, 4].

My solution was to do the following

[3] + ([1, 2, 3, 4] - [3])

Is there a better way to do this?


Solution

  • A method that takes the first n elements from an array and rotates them by one, then adds back the remaining elements.

    def rotate_first_n_right(arr, n)
      arr[0...n].rotate(-1) + arr[n..-1]
    end
    
    rotate_first_n_right([1,2,3,4], 3)
    # => [3, 1, 2, 4]
    

    This does fail if we try to use it on an array that is too short, as the arr[n..-1] slice will yield nil which will cause an error when we try to add it to the first array.

    We can fix this by expanding both slices into a list.

    def rotate_first_n_right(arr, n)
      [*arr[0...n].rotate(-1), *arr[n..-1]]
    end
    

    To see why this works, a very simple example:

    [*[1, 2, 3], *nil]
    # => [1, 2, 3]
    

    A problem with your example is what happens if 3 occurs in the array more than once. E.g.

    [1,2,3,3,3,4] - [3]
    # => [1, 2, 4]