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
The shift() method removes the first element from an array and returns that removed element. This method changes the length of the 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!
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.
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!
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"]
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]
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