我想不出一条直线的方法。有办法吗?
当前回答
你可以结合使用prepend和delete,它们都是惯用的,也都能透露出你的意图:
array.delete(value) # Remove the value from the array
array.prepend(value) # Add the value to the beginning of the array
或在单行中:
array.prepend(array.delete(value))
其他回答
使用unshift方法怎么样?
必要。Unshift (obj,…)→ary 将对象前置到self的前面,将其他元素向上移动。
并在使用中:
irb>> a = [ 0, 1, 2]
=> [0, 1, 2]
irb>> a.unshift('x')
=> ["x", 0, 1, 2]
irb>> a.inspect
=> "["x", 0, 1, 2]"
你也可以使用数组连接:
a = [2, 3]
[1] + a
=> [1, 2, 3]
这将创建一个新数组,并且不修改原始数组。
array = ["foo"]
array.unshift "bar"
array
=> ["bar", "foo"]
警告,这是毁灭性的!
你可以结合使用prepend和delete,它们都是惯用的,也都能透露出你的意图:
array.delete(value) # Remove the value from the array
array.prepend(value) # Add the value to the beginning of the array
或在单行中:
array.prepend(array.delete(value))
从Ruby 2.5.0开始,Array附带了prepend方法(这只是unshift方法的别名)。