假设我有一个数组
[0, 132, 432, 342, 234]
去掉第一个元素最简单的方法是什么?(0)
假设我有一个数组
[0, 132, 432, 342, 234]
去掉第一个元素最简单的方法是什么?(0)
当前回答
或者a.delete_at 0
其他回答
[0, 132, 432, 342, 234][1..]
=> [132, 432, 342, 234]
因此,与shift或slice不同,这将返回一个新数组,保持原始数组不变(对于一行程序很有用)。
在数组上使用shift方法
>> x = [4,5,6]
=> [4, 5, 6]
>> x.shift
=> 4
>> x
=> [5, 6]
如果你想移除n个起始元素你可以使用x.shift(n)
这很简洁:
head, *tail = [1, 2, 3, 4, 5]
#==> head = 1, tail = [2, 3, 4, 5]
正如评论中所写的,不改变原始列表的优点。
使用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
你可以使用:
a.slice!(0)
片!泛化到任何索引或范围。