Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

ruby
communitycreator

What is array.shift in Ruby?

okwudili onyejiaku

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 elements
array1 = [1, 2, 3]
array2 = ["a", "b", "c"]
array3 = ["Javascript", "Python", "C++"]

# remove first elements
a = array1.shift
b = array2.shift
c = array3.shift

# print values to the console
puts "#{a}"     # 1 
puts "#{b}"     # a
puts "#{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 elements
array1 = [1, 2, 3]
array2 = ["a", "b", "c"]
array3 = ["Javascript", "Python", "C++"]

# remove "n" number of elements
a = array1.shift(2)
b = array2.shift(3)
c = array3.shift(1)

# print values to the console
puts "#{a}"     # [1, 2]
puts "#{b}"     # ["a", "b", "c"]
puts "#{c}"     # Javascript

# print modified array
puts "#{array1}"  # [3]
puts "#{array2}"  # []
puts "#{array3}"  # ["Python", "C++"]

RELATED TAGS

ruby
communitycreator
RELATED COURSES

View all Courses

Keep Exploring