How to change the position of an array element?

Explanation for beginners

These answers are great. I was looking for a little more explanation on how these answers work. Here's what's happening in the answers above, how to switch elements by value, and links to documentation.

# sample array
arr = ["a", "b", "c", "d", "e", "f", "g", "h"]

# suppose we want to move "h" element in position 7 to position 2 (trekd's answer)
arr = arr.insert(2, arr.delete_at(7))
=> ["a", "b", "h", "c", "d", "e", "f", "g"]

This works because arr.delete_at(index) deletes the elements at the specified index ('7' in our example above), and returns the value that was in that index. So, running arr.delete_at(7) would produce:

# returns the deleted element
arr.delete_at(7) 
=> "h"           

# array without "h"
arr
=> ["a", "b", "c", "d", "e", "f", "g"]

Putting it together, the insert method will now place this "h" element at position 2. Breaking this into two steps for clarity:

# delete the element in position 7
element = arr.delete_at(7)  # "h"
arr.insert(2, element)
=> ["a", "b", "h", "c", "d", "e", "f", "g"]

Switching elements by value

Suppose you wanted to move the element in the array whose value is "h", regardless of its position, to position 2. This can easily be accomplished with the index method:

arr = arr.insert(2, arr.delete_at( arr.index("h") ))

Note: The above assumes that there's only one value of "h" in the array.

Documentation

  • Array#delete_at
  • Array#insert
  • Array#index

Nothing is simpler:

array.insert(2, array.delete_at(7))

irb> a = [2,5,4,6]
=> [2, 5, 4, 6]
irb> a.insert(1,a.delete_at(3))
=> [2, 6, 5, 4]

Tags:

Arrays

Ruby