我想不出一条直线的方法。有办法吗?
使用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]"
您可以使用方法求解器来查找Ruby函数。
这是一个小脚本,
require 'methodsolver'
solve { a = [1,2,3]; a.____(0) == [0,1,2,3] }
运行这个指纹
Found 1 methods
- Array#unshift
您可以使用
gem install methodsolver
你可以结合使用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))