a = [1,2,3]
b = [2,1,3]
从b
获取a
的最佳方法是什么?
我不优雅的解决方案:
x = 2
y = a - [x]
b = y.unshift(x)
答案 0 :(得分:5)
a.unshift a.delete(2)
这会附加最近删除的对象(此处为2
)。
请注意,如果有问题的对象在阵列中出现多次,则所有出现的内容都将被删除。
如果您只想移动第一次出现的对象,请尝试:
a = [1,2,3,2]
a.unshift a.delete_at(a.index(2))
# => [2, 1, 3, 2]
答案 1 :(得分:0)
a.unshift a.slice!(a.index(2)||0)
# => [2, 1, 3]
a
不变。答案 2 :(得分:0)
如果你想任意移动数组的元素,你可以这样做:
<强>代码强>
# Return a copy of the receiver array, with the receiver's element at
# offset i moved before the element at offset j, unless j == self.size,
# in which case the element at offset i is moved to the end of the array.
class Array
def move(i,j)
a = dup
case
when i < 0 || i >= size
raise ArgumentError, "From index is out-of-range"
when j < 0 || j > size
raise ArgumentError, "To index is out-of-range"
when j < i
a.insert(j, a.delete_at(i))
when j == size
a << a.delete_at(i)
when j > i+1
a.insert(j-1, a.delete_at(i))
else
a
end
end
end
使用Ruby v2.1,您可以选择将class Array
替换为refine Array
。 (Module#refine是在v2.0中通过实验引入的,但在v2.1中已经有了实质性的改变。)
<强>演示强>
arr = [1,2,3,4,5] #=> [1, 2, 3, 4, 5]
arr.move(2,1) #=> [1, 3, 2, 4, 5]
arr.move(2,2) #=> [1, 2, 3, 4, 5]
arr.move(2,3) #=> [1, 2, 3, 4, 5]
arr.move(2,4) #=> [1, 2, 4, 3, 5]
arr.move(2,5) #=> [1, 2, 4, 5, 3]
arr.move(2,6) #=> ArgumentError: To index is out-of-range