34

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?

8 Answers 8

58

Nothing is simpler:

array.insert(2, array.delete_at(7))
4
  • 8
    Ok, now reverse direction. Position 2 to position 7. Maybe not so simple as you think.
    – wizzard
    Aug 18, 2015 at 5:59
  • 3
    This does not work if you're moving from an index that is before the index you're inserting at! The act of removing will occur before the insertion, so you need to account for the elements shifting before you insert.
    – DanF
    Dec 11, 2015 at 19:43
  • 8
    The above comments are wrong, this approach works in all cases. Try it yourself in irb.
    – ToddH
    Jan 19, 2016 at 4:04
  • This answer is misleading. While it works, and answers the question, @wizzard is right in that it doesn't work in all scenarios. See my answer below for a way that works in the scenario where the origin index is less than the destination index. Oct 26, 2018 at 6:22
27
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

2
  • 1
    Thanks for your correct answer. I gave trekd the correct answer, as he still has the newbie bonus.
    – Markus
    Jan 19, 2011 at 10:28
  • I would expect [0,2,3,1,4] and I'll explain why in my updated answer. Mar 23 at 3:12
10

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

2
  • Switching elements by value -> What if you have more "h" May 20, 2020 at 3:28
  • @AdamLudian you'll just need to be specific as to the behaviour you want. For example, if your array has more than one "h" value, maybe you wouldn't want to run this code at all.
    – Matt
    May 26, 2020 at 23:13
4

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]
1
  • 1
    Although neat, this swaps two positions which isn't what the original poster requested. They wanted to move item 7 to item 2. So technically this doesn't answer the question. Oct 23, 2019 at 11:30
3

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.

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)

For Clarification

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.

7
  • I downvoted because this is wrong. You can view Nakilon's answer to see it demonstrated.
    – fatfrog
    Mar 22 at 14:08
  • @fatfrog, please re-read my answer and note that Nakilon's example shows deleting an item from the array at an index that is higher than the index he is inserting it at. That works well as-is but will fail if the reverse is true since the delete operation happens before the insert operation it will affect the index of the item you're targeting to insert before. Mar 22 at 20:28
  • Nakilon updated his answer to include the destination > origin. Next time work on verifying your answer. At least 2 poor chumps may have buggy code now.
    – fatfrog
    Mar 23 at 3:00
  • @fatfrog, I've clarified my position. In my opinion, blindly copying Nakilon's one liner is much more likely to lead to buggy code but it all really depends on ones assumptions about the indexes you're targeting to begin with. Mar 23 at 3:31
  • "Has this achieved my intended result?" Yes it has - :jane is now at index 3
    – fatfrog
    Mar 23 at 20:19
0

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]

?

1
  • 2
    This only works if you want to move the last element, but doesn't work if you want to move another one :) Mar 2, 2017 at 13:56
0

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

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.