Ruby:从数组中删除第一个元素的最简单方法是什么?
可以说我有一个数组
[0, 132, 432, 342, 234] 什么是摆脱第一个元素的最简单的方法? (0)
“popup”一个数组的第一个元素被称为“ 移位 ”(“不移位 ”是在数组前添加一个元素的操作)。
 在数组上使用shift方法 
 >> x = [4,5,6] => [4, 5, 6] >> x.shift => 4 >> x => [5, 6] 
 如果你想删除n个起始元素,你可以使用x.shift(n) 
 a = [0,1,2,3] a.drop(1) # => [1, 2, 3] a # => [0,1,2,3] 
另外:
 [0,1,2,3].drop(2) => [2, 3] [0,1,2,3].drop(3) => [3] 
 [0, 132, 432, 342, 234][1..-1] => [132, 432, 342, 234] 
 所以,不像shift或slice它会返回修改后的数组(对于一个内衬很有用)。 
这很整齐:
 head, *tail = [1, 2, 3, 4, 5] #==> head = 1, tail = [2, 3, 4, 5] 
正如在评论中所写的,有一个优点是不会改变原始列表。
 或a.delete_at 0 
您可以使用:
 a.slice!(0) 
片! 概括为任何索引或范围。
使用移位法
 array.shift(n) => Remove first n elements from array array.shift(1) => Remove first element 
你可以使用Array.delete_at(0)方法删除第一个元素。
  x = [2,3,4,11,0] x.delete_at(0) unless x.empty? # [3,4,11,0] 
 您可以使用: 
  arr - [arr[0]]或者arr - [arr.shift()]或者简单的arr.shift(1)