mu *_*ort 369
怎么用这个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]"
Run Code Online (Sandbox Code Playgroud)
Ed *_* S. 44
你可以使用insert:
a = [1,2,3]
a.insert(0,'x')
=> ['x',1,2,3]
Run Code Online (Sandbox Code Playgroud)
第一个参数是要插入的索引,第二个参数是值.
Joh*_*n H 21
array = ["foo"]
array.unshift "bar"
array
=> ["bar", "foo"]
Run Code Online (Sandbox Code Playgroud)
被警告,这是破坏性的!
ma1*_*w28 10
您还可以使用数组连接:
a = [2, 3]
[1] + a
=> [1, 2, 3]
Run Code Online (Sandbox Code Playgroud)
这将创建一个新数组,但不会修改原始数组.
您可以使用它methodsolver来查找Ruby函数.
这是一个小脚本,
require 'methodsolver'
solve { a = [1,2,3]; a.____(0) == [0,1,2,3] }
Run Code Online (Sandbox Code Playgroud)
运行此打印
Found 1 methods
- Array#unshift
Run Code Online (Sandbox Code Playgroud)
您可以使用安装methodsolver
gem install methodsolver
Run Code Online (Sandbox Code Playgroud)
从Ruby 2.5.0开始,Array随该prepend 方法一起提供(这只是该unshift方法的别名)。
| 归档时间: |
|
| 查看次数: |
97894 次 |
| 最近记录: |