What is array.shift in Ruby?
The array.shift() method in Ruby removes the first element of an array and returns the removed element.
If an array is empty and the shift() method is called on it, the method returns null or nothing.
Syntax
array.shift
# OR
array.shift(n)
Parameters
n: When n is passed, the method returns an array that contains the first n elements. This parameter is optional.
Return value
The shift() method returns the first removed element. If n is passed, the method returns the remaining elements of the array.
Code
In the example below, we create several arrays and use the shift method to remove the first element of each array.
# Initializing some arrays of elementsarray1 = [1, 2, 3]array2 = ["a", "b", "c"]array3 = ["Javascript", "Python", "C++"]# remove first elementsa = array1.shiftb = array2.shiftc = array3.shift# print values to the consoleputs "#{a}" # 1puts "#{b}" # aputs "#{c}" # Javascript
Pass the n argument
When the n argument is passed to the shift method, the first n elements are removed and the remaining elements are returned.
# Initializing some arrays of elementsarray1 = [1, 2, 3]array2 = ["a", "b", "c"]array3 = ["Javascript", "Python", "C++"]# remove "n" number of elementsa = array1.shift(2)b = array2.shift(3)c = array3.shift(1)# print values to the consoleputs "#{a}" # [1, 2]puts "#{b}" # ["a", "b", "c"]puts "#{c}" # Javascript# print modified arrayputs "#{array1}" # [3]puts "#{array2}" # []puts "#{array3}" # ["Python", "C++"]