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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 23:08:10  来源:igfitidea点击:

Ruby: What is the easiest way to remove the first element from an array?

ruby-on-railsruby

提问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

"pop"ing the first element of an Array is called "shift" ("unshift" being the operation of adding one element in front of the array).

“弹出”数组的第一个元素称为“移位”(“unshift”是在数组前面添加一个元素的操作)。

回答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).

所以不同shiftslice这返回修改后的数组(对一个班轮有用)。

回答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

https://ruby-doc.org/core-2.2.0/Array.html#method-i-shift

https://ruby-doc.org/core-2.2.0/Array.html#method-i-shift

回答by Matthew Flaschen

You can use:

您可以使用:

a.slice!(0)

slice!generalizes to any index or range.

片!推广到任何索引或范围。

回答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

两者都可以工作