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?
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]
UPD: guys, it works fine with the dest>src:
a = [0,1,2,3,4]
a.insert 1, a.delete_at(3)
p a #=> [0, 3, 1, 2, 4]
a = [0,1,2,3,4]
a.insert 3, a.delete_at(1)
p a #=> [0, 2, 3, 1, 4]
What else would you expect? 0,2,1,3,4? I would not call that dest=3
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 in case you want to swap:
array = [4, 5, 6, 7]
array[0], array[3] = array[3], array[0]
array # => [7, 5, 6, 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.
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)
It may help to think of this problem in less numerical terms. Consider:
employees = [:bob, :jane, :steve, :tama, :susan]
I want to move :jane
in front of :tama
. I see that :jane
is at position 1
and :tama
is at position 3
currently. I think I'll be efficient and do this as a one-liner based upon the positions I know to be true right now:
employees.insert 3, employees.delete_at(1)
Has this achieved my intended result? No, :jane
is after :tama
.
[:bob, :steve, :tama, :jane, :susan]
Why does this happen? Because the index of the members of the array change above the point of the deleted member, so the index you assumed was referencing the member before the delete_at
has now changed. To do this properly you'd be better off first removing :jane
, then looking at the employees
again to ascertain the index of :tama
which is now 2
not 3
, then inserting :jane
at 2
instead.
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 are looking for solution to move uniq items up and down the array:
module ArrayElementMove
MustBeUniqArray = Class.new(StandardError)
ItemNotInArray = Class.new(StandardError)
def self.up!(array, item)
self.check_if_uniq!(array)
return array if array.first == item
position = array.index(item) || raise(ItemNotInArray)
array.insert((position - 1), array.delete_at(position))
end
def self.down!(array, item)
self.check_if_uniq!(array)
return array if array.last == item
position = array.index(item) || raise(ItemNotInArray)
array.insert((position + 1), array.delete_at(position))
end
def self.check_if_uniq!(array)
raise MustBeUniqArray if array.size != array.uniq.size
end
end
spec:
require 'spec_helper'
RSpec.describe ArrayElementMove do
let(:arr) { [1,2,3,4,5,6] }
it do
ArrayElementMove.up!(arr, 4)
expect(arr).to eq([1,2,4,3,5,6])
expect(ArrayElementMove.up!(arr, 4).to eq([1,4,2,3,5,6])
expect(arr).to eq([1,4,2,3,5,6])
ArrayElementMove.up!(arr, 4)
expect(arr).to eq([4,1,2,3,5,6])
ArrayElementMove.up!(arr, 4)
expect(arr).to eq([4,1,2,3,5,6])
end
it do
ArrayElementMove.down!(arr, 4)
expect(arr).to eq([1,2,3,5,4,6])
expect(ArrayElementMove.down!(arr, 4)).to eq([1,2,3,5,6,4])
expect(arr).to eq([1,2,3,5,6,4])
expect(ArrayElementMove.down!(arr, 4)).to eq([1,2,3,5,6,4])
expect(arr).to eq([1,2,3,5,6,4])
end
context 'when non uniq array' do
let(:arr) { [1,4,2,3,4,5,6] }
it do
expect { ArrayElementMove.down!(arr, 3) }.to raise_exception(ArrayElementMove::MustBeUniqArray)
expect(arr).to eq([1,4,2,3,4,5,6])
end
it do
expect { ArrayElementMove.down!(arr, 3) }.to raise_exception(ArrayElementMove::MustBeUniqArray)
expect(arr).to eq([1,4,2,3,4,5,6])
end
end
context 'when non existing item' do
it do
expect { ArrayElementMove.up!(arr, 9) }.to raise_exception(ArrayElementMove::ItemNotInArray)
expect(arr).to eq([1,2,3,4,5,6])
end
it do
expect { ArrayElementMove.up!(arr, 9) }.to raise_exception(ArrayElementMove::ItemNotInArray)
expect(arr).to eq([1,2,3,4,5,6])
end
end
end