如何更改数组元素的位置?

我有一个关于如何更改数组元素索引的问题,因此它不会出现在7.位置而是位于2位而是…

是否有处理此function的function?

没有比这更简单的了:

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] 

如果你不关心数组中其他元素的位置,你可以使用.rotate! (注意,此方法末尾的!更改实际数组)方法。

 arr = [1, 2, 3, 4, 5, 6, 7, 8] arr.rotate! -3 arr = [6, 7, 8, 1, 2, 3, 4, 5] 

这将获取索引为7的元素8,并将其旋转为索引2。

初学者的解释

这些答案很棒。 我正在寻找关于这些答案如何运作的更多解释。 以下是上述答案中发生的情况,如何按值切换元素以及指向文档的链接。

 # 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"] 

这是有效的,因为arr.delete_at(index)删除指定索引处的元素(在上面的示例中为’7’),并返回该索引中的值。 因此,运行arr.delete_at(7)会产生:

 # returns the deleted element arr.delete_at(7) => "h" # array without "h" arr => ["a", "b", "c", "d", "e", "f", "g"] 

将它放在一起, insert方法现在将这个“h”元素放在位置2.为了清楚起见,将其分为两个步骤:

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

按值切换元素

假设您想要将值为“h”的数组中的元素(无论其位置如何)移动到位置2.这可以使用索引方法轻松完成:

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

注意:以上假设数组中只有一个“h”值。

文档

  • arrays#delete_at
  • arrays插入#
  • 数组索引#

最好的办法..

 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.pop) #=> [2, 6, 5, 4] 

这里的答案不包括两种可能的情况。 虽然问题涉及的origin索引高于destination ,但如果反之则为真,则下面的解决方案将不起作用:

 array.insert 7, array.delete_at(2) 

这是因为删除2处的值会将数组中的所有内容(大于2)向下移动1.现在,我们的目标索引7指向过去在索引8处的内容。

要解决此问题,我们需要检查origin是否小于destination ,如果是,则从destination扣除1。

 origin = 2 destination = 7 destination -= 1 if origin < destination array.insert destination, array.delete_at(origin)