Ger*_*osi 51
没有比这更简单的了:
array.insert(2, array.delete_at(7))
Run Code Online (Sandbox Code Playgroud)
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”值。