Ruby:从数组中删除第一个元素的最简单方法是什么?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3615700/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Ruby: What is the easiest way to remove the first element from an array?
提问by NullVoxPopuli
Lets say I have an array
假设我有一个数组
[0, 132, 432, 342, 234]
What is the easiest way to get rid of the first element? (0)
摆脱第一个元素的最简单方法是什么?(0)
回答by scaryguy
a = [0,1,2,3]
a.drop(1)
# => [1, 2, 3]
a
# => [0,1,2,3]
and additionally:
此外:
[0,1,2,3].drop(2)
=> [2, 3]
[0,1,2,3].drop(3)
=> [3]
回答by bragboy
Use the shiftmethod on array
shift在数组上使用该方法
>> x = [4,5,6]
=> [4, 5, 6]
>> x.shift
=> 4
>> x
=> [5, 6]
If you want to remove n starting elements you can use x.shift(n)
如果你想删除 n 个起始元素,你可以使用 x.shift(n)
回答by Sjoerd
回答by vise
[0, 132, 432, 342, 234][1..-1]
=> [132, 432, 342, 234]
So unlike shiftor slicethis returns the modified array (useful for one liners).
所以不同shift或slice这返回修改后的数组(对一个班轮有用)。
回答by hurikhan77
This is pretty neat:
这很整洁:
head, *tail = [1, 2, 3, 4, 5]
#==> head = 1, tail = [2, 3, 4, 5]
As written in the comments, there's an advantage of not mutating the original list.
正如评论中所写,不改变原始列表有一个优势。
回答by zzzhc
or a.delete_at 0
或者 a.delete_at 0
回答by Rahul Patel
Use shift method
使用移位方法
array.shift(n) => Remove first n elements from array
array.shift(1) => Remove first element
回答by Matthew Flaschen
回答by lalit.sethi143
You can use Array.delete_at(0) method which will delete first element.
您可以使用 Array.delete_at(0) 方法来删除第一个元素。
x = [2,3,4,11,0]
x.delete_at(0) unless x.empty? # [3,4,11,0]
回答by sam
You can use:
您可以使用:
a.delete(a[0])
a.delete_at 0
Both can work
两者都可以工作

