我想不出一条直线的方法。有办法吗?
当前回答
您可以使用方法求解器来查找Ruby函数。
这是一个小脚本,
require 'methodsolver'
solve { a = [1,2,3]; a.____(0) == [0,1,2,3] }
运行这个指纹
Found 1 methods
- Array#unshift
您可以使用
gem install methodsolver
其他回答
array = ["foo"]
array.unshift "bar"
array
=> ["bar", "foo"]
警告,这是毁灭性的!
你也可以使用数组连接:
a = [2, 3]
[1] + a
=> [1, 2, 3]
这将创建一个新数组,并且不修改原始数组。
你可以结合使用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]"
你可以使用insert:
a = [1,2,3]
a.insert(0,'x')
=> ['x',1,2,3]
第一个参数是要插入的索引,第二个参数是值。
推荐文章
- 如何在Java中将int[]转换为Integer[] ?
- 在Ruby中不创建新字符串而修饰字符串的规范方法是什么?
- c++中有最大数组长度限制吗?
- RVM不是一个函数,用' RVM use…’不会起作用
- 如何在c#中连接列表?
- 在JavaScript中根据键值查找和删除数组中的对象
- 了解Gemfile。锁文件
- 如何确定一个数组是否包含另一个数组的所有元素
- 给定一个数字数组,返回所有其他数字的乘积的数组(不除法)
- 多维数组如何在内存中格式化?
- 是什么导致这个ActiveRecord::ReadOnlyRecord错误?
- TypeScript枚举对象数组
- 最好的打印散列的方法
- 获取数组值的键名
- Rails:dependent =>:destroy VS:dependent =>:delete_all