Lets say I have an array
[0, 132, 432, 342, 234]
What is the easiest way to get rid of the first element? (0)
shift() The shift() method removes the first element from an array and returns that removed element. This method changes the length of the array.
Most efficient way to remove an element from an array, then reduce the size of the array.
The pop() function in Ruby is used to pop or remove the last element of the given array and returns the removed elements.
.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]
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With