Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to change the position of an array element?

Tags:

arrays

ruby

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 handle this?

like image 400
Markus Avatar asked Jan 19 '11 10:01

Markus


People also ask

How do you move an array to the left?

The array can be left rotated by shifting its elements to a position prior to them which can be accomplished by looping through the array and perform the operation arr[j] = arr[j+1]. The first element of the array will be added to the last of rotated array.


2 Answers

Nothing is simpler:

array.insert(2, array.delete_at(7))
like image 172
Gergõ Sulymosi Avatar answered Oct 15 '22 01:10

Gergõ Sulymosi


irb> a = [2,5,4,6]
=> [2, 5, 4, 6]
irb> a.insert(1,a.delete_at(3))
=> [2, 6, 5, 4]
like image 25
Nakilon Avatar answered Oct 14 '22 23:10

Nakilon