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

Mar*_*kus 26 ruby arrays

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

有没有处理这个的功能?

Ger*_*osi 51

没有比这更简单的了:

array.insert(2, array.delete_at(7))
Run Code Online (Sandbox Code Playgroud)

  • 好的,现在反方向.位置2到位置7.也许并不像你想象的那么简单. (7认同)
  • 以上评论是错误的,这种方法适用于所有情况.在irb中自己尝试一下. (6认同)
  • 如果您从正在插入索引之前的索引移动,则此方法无效!删除操作将在插入之前进行,因此您需要在插入之前考虑元素移位. (2认同)

Nak*_*lon 23

irb> a = [2,5,4,6]
=> [2, 5, 4, 6]
irb> a.insert(1,a.delete_at(3))
=> [2, 6, 5, 4]
Run Code Online (Sandbox Code Playgroud)


Mat*_*att 10

初学者的解释

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

# 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"]
Run Code Online (Sandbox Code Playgroud)

这是有效的,因为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"]
Run Code Online (Sandbox Code Playgroud)

放在一起,该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"]
Run Code Online (Sandbox Code Playgroud)

按值切换元素

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

arr = arr.insert(2, arr.delete_at( arr.index("h") ))
Run Code Online (Sandbox Code Playgroud)

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

文档