我想不出一种一行代码解决这个问题的方法。有其他办法吗?
可以尝试使用 unshift
方法。
ary.unshift(obj, ...) → ary
将对象添加到 self 的前面,移动其他元素。
用法示例:
a = [ 0, 1, 2]
a.unshift('x')
# => ["x", 0, 1, 2]
a.inspect
# => "["x", 0, 1, 2]"
您可以使用insert
:
a = [1,2,3]
a.insert(0,'x')
=> ['x',1,2,3]
第一个参数是要插入的索引位置,第二个参数是要插入的值。
array = ["foo"]
array.unshift "bar"
array
=> ["bar", "foo"]
注意,它会造成破坏!
自 Ruby 2.5.0 版本开始,Array 类中新增了 prepend
方法(该方法是 unshift
方法的别名)。
您可以使用methodsolver
来查找Ruby函数。
这是一个小脚本,
require 'methodsolver'
solve { a = [1,2,3]; a.____(0) == [0,1,2,3] }
运行此代码将会打印出:
Found 1 methods
- Array#unshift
您可以使用以下方法安装 methodsolver:
gem install methodsolver
irb> require 'methodsolver'
会导致 LoadError: cannot load such file -- method_source
错误,错误来源为 /var/lib/gems/1.9.1/gems/methodsolver-0.0.4/lib/methodsolver.rb:2
。 - Camille Goudeseunepry
而不是 irb
。 - akuhnprepend
和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))
shift
和unshift
的区别上有困难,不知道哪个是向数组添加元素,哪个是从数组中删除元素,可以在心理上将它们的名称中的“f”去掉,这样就能非常清晰地看出它们的方向了。(然后你还需要记住这些方法不能在数组的“末尾”使用。;) - Phrogz