remove an element from the beginning of an array in ruby

To remove an element from the beginning of an array in Ruby, you can use the shift method which mutates the original array. Here's an example:

main.rb
arr = [1, 2, 3, 4, 5]
arr.shift #=> 1
arr #=> [2, 3, 4, 5]
59 chars
4 lines

This removes the first element from the array arr and returns it. Note that the original array is mutated as a result, so arr now contains the remaining elements after the first element has been removed.

Alternatively, you could also use indexing to achieve the same result, although this would not mutate the original array:

main.rb
arr = [1, 2, 3, 4, 5]
arr[1..-1] #=> [2, 3, 4, 5]
50 chars
3 lines

To remove the first element, we slice the array from index 1 (the second element) to the end using a range. This returns a new array containing all elements except the first one. Note that the original array arr remains unchanged in this case.

gistlibby LogSnag