How to change the position of an array element?

后端 未结 7 817
Happy的楠姐
Happy的楠姐 2020-12-24 06:45

I have a question on how I can change the index of a array element, so that it doesn\'t come at the 7. position but at position 2 instead...

Is there a function to h

7条回答
  •  抹茶落季
    2020-12-24 07:03

    If you don't care about the position of the other elements in the array you can use the .rotate! (note that the ! at the end of this method changes the actual array) method.

    arr = [1, 2, 3, 4, 5, 6, 7, 8]
    arr.rotate! -3
    arr = [6, 7, 8, 1, 2, 3, 4, 5]
    

    This takes the element 8 which is at index 7, and rotates it to an index of 2.

提交回复
热议问题