【发布时间】:2011-08-30 10:35:50
【问题描述】:
我想不出一种单一的方法来做到这一点。有什么办法吗?
【问题讨论】:
我想不出一种单一的方法来做到这一点。有什么办法吗?
【问题讨论】:
你可以使用insert:
a = [1,2,3]
a.insert(0,'x')
=> ['x',1,2,3]
第一个参数是要插入的索引,第二个是值。
【讨论】:
使用unshift 方法怎么样?
ary.unshift(obj, ...) → ary
将对象添加到自身前面,向上移动其他元素。
并在使用中:
irb>> a = [ 0, 1, 2]
=> [0, 1, 2]
irb>> a.unshift('x')
=> ["x", 0, 1, 2]
irb>> a.inspect
=> "["x", 0, 1, 2]"
【讨论】:
shift 和 unshift 之间的哪些添加到数组中,哪些从数组中删除,请在脑海中从名称中删除一个“f”,然后您将得到一个全部- 方向图太清晰。 (然后您必须记住,这些方法不适用于数组的“末端”。;)
array = ["foo"]
array.unshift "bar"
array
=> ["bar", "foo"]
请注意,这是破坏性的!
【讨论】:
【讨论】:
您可以使用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。红宝石 1.9.3p484,irb 0.9.6,Ubuntu 14。
pry 而不是irb
自 Ruby 2.5.0 起,Array 附带了 prepend 方法(它只是 unshift 方法的别名)。
【讨论】:
您可以使用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))
【讨论】: