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
The answers here don't cover both possible scenarios. While the question dealt with an origin
index higher than the destination
, if the reverse is true then the solution below won't work:
array.insert 7, array.delete_at(2)
This is because deleting the value at 2 shifts everything (above 2) down the array by 1. Now our destination index of 7 is pointing at what used to be at index 8.
To fix this, we need to check if the origin
is less than the destination
and if so, deduct 1 from the destination
.
origin = 2
destination = 7
destination -= 1 if origin < destination
array.insert destination, array.delete_at(origin)
Isn't better to use:
irb> a = [2,5,4,6]
#=> [2, 5, 4, 6]
irb> a.insert(1, a.pop)
#=> [2, 6, 5, 4]
?
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.
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"]
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.
Best way..
array = [4, 5, 6, 7]
array[0], array[3] = array[3], array[0]
array # => [7, 5, 6, 4]
irb> a = [2,5,4,6]
=> [2, 5, 4, 6]
irb> a.insert(1,a.delete_at(3))
=> [2, 6, 5, 4]