Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Delete first x entires of an array

Tags:

I have an array of items, and I need to delete the first x items of it. Is there a built-in function in the Ruby Array class to do this? I had a search around and only found, what looked like, incredibly messy or inefficient ways to do it.

I'd preferably like something like this:

my_items = [ 'item1', 'item2', 'item3', 'item4' ] trimmed_items = my_items.delete(y, x) # deleting x entries from index y 
like image 566
Alexander Forbes-Reed Avatar asked Jul 22 '13 14:07

Alexander Forbes-Reed


People also ask

How do you remove the first data from an array?

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

How do you remove the first two elements of an array?

To remove the first 2 elements from an array, call the splice() method, passing it 0 and 2 as parameters, e.g. arr. splice(0, 2) . The splice method will delete the first two elements from the array and return a new array containing the deleted elements. Copied!

How do you delete a specific data from an array?

pop() function: This method is use to remove elements from the end of an array. shift() function: This method is use to remove elements from the start of an array. splice() function: This method is use to remove elements from the specific index of an array.

How do you delete the first and last elements of an array?

To remove the first and last elements from an array, call the shift() and pop() methods on the Array. The shift method removes the first and the pop method removes the last element from an array. Both methods return the removed elements. Copied!


2 Answers

I have an array of items, and I need to delete the first x items of it.

To non-destructive deletion

Array#drop(x) will do the work for you.

Drops first n elements from ary and returns the rest of the elements in an array.If a negative number is given, raises an ArgumentError.

my_items = [ 'item1', 'item2', 'item3', 'item4' ] p my_items.drop(2) p my_items  # >>["item3", "item4"] # >>["item1", "item2", "item3", "item4"] 

To destructive deletion

Array#shift

Removes the first element of self and returns it (shifting all other elements down by one). Returns nil if the array is empty.If a number n is given, returns an array of the first n elements (or less) just like array.slice!(0, n) does.

my_items = [ 'item1', 'item2', 'item3', 'item4' ] my_items.shift(2) p my_items # => ["item3", "item4"] 
like image 93
Arup Rakshit Avatar answered Sep 28 '22 18:09

Arup Rakshit


Yet another way to accomplish this: use Array#shift, which is particularly useful when you want the values that you're removing from the front of the array.

a = (1..5).to_a a.shift(2) a # => [3, 4, 5] 
like image 32
Mark Rushakoff Avatar answered Sep 28 '22 18:09

Mark Rushakoff