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.rb59 chars4 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.rb50 chars3 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