Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Lets say I have an array

[0, 132, 432, 342, 234] 

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

like image 967
NullVoxPopuli Avatar asked Sep 01 '10 07:09

NullVoxPopuli


People also ask

How do I remove the first element from an array?

shift() The shift() method removes the first element from an array and returns that removed element. This method changes the length of the array.

What is the most efficient way to remove an element from an array?

Most efficient way to remove an element from an array, then reduce the size of the array.

How do you remove the last element of an array in Ruby?

The pop() function in Ruby is used to pop or remove the last element of the given array and returns the removed elements.


2 Answers

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]  
like image 157
scaryguy Avatar answered Oct 06 '22 14:10

scaryguy


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)

like image 37
bragboy Avatar answered Oct 06 '22 12:10

bragboy