277
votes

Lets say I have an array

[0, 132, 432, 342, 234]

What is the easiest way to get rid of the first element? (0)

11
'shift' is pop and 'unshift' is push. In which shift takes in the number of parameters to pop - Arun

11 Answers

307
votes

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

396
votes
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] 
311
votes

Use the shift method on array

>> 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)

135
votes
[0, 132, 432, 342, 234][1..-1]
=> [132, 432, 342, 234]

So unlike shift or slice this returns the modified array (useful for one liners).

107
votes

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.

18
votes

or a.delete_at 0

16
votes

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

12
votes

You can use:

a.slice!(0)

slice! generalizes to any index or range.

5
votes

You can use Array.delete_at(0) method which will delete first element.

 x = [2,3,4,11,0]
 x.delete_at(0) unless x.empty? # [3,4,11,0]
2
votes

You can use:

 a.delete(a[0])   
 a.delete_at 0

Both can work

2
votes

You can use:

arr - [arr[0]]

or

arr - [arr.shift]

or simply

arr.shift(1)