假设我有一个数组
[0, 132, 432, 342, 234]
去掉第一个元素最简单的方法是什么?(0)
假设我有一个数组
[0, 132, 432, 342, 234]
去掉第一个元素最简单的方法是什么?(0)
当前回答
你可以使用:
a.slice!(0)
片!泛化到任何索引或范围。
其他回答
使用shift法
array.shift(n) => Remove first n elements from array
array.shift(1) => Remove first element
https://ruby-doc.org/core-2.2.0/Array.html#method-i-shift
在数组上使用shift方法
>> x = [4,5,6]
=> [4, 5, 6]
>> x.shift
=> 4
>> x
=> [5, 6]
如果你想移除n个起始元素你可以使用x.shift(n)
你可以使用:
a.slice!(0)
片!泛化到任何索引或范围。
[0, 132, 432, 342, 234][1..]
=> [132, 432, 342, 234]
因此,与shift或slice不同,这将返回一个新数组,保持原始数组不变(对于一行程序很有用)。
你可以使用:
a.delete(a[0])
a.delete_at 0
两者都可以