Ruby: What is the easiest way to remove the first element from an array?
Solution 1:
Use .drop(1)
.
This has the benefit of returning a new Array with the first element removed, as opposed to using .shift
, which returns the removed element, not the Array with the first element removed.
NOTE: It does not affect/mutate the original Array.
a = [0,1,2,3]
a.drop(1)
# => [1, 2, 3]
a
# => [0,1,2,3]
And, additionally, you can drop more than the first element:
[0,1,2,3].drop(2)
=> [2, 3]
[0,1,2,3].drop(3)
=> [3]
Solution 2:
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)
Solution 3:
"pop"ing the first element of an Array is called "shift" ("unshift" being the operation of adding one element in front of the array).
Solution 4:
[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).