How to Use the Ruby shift Method

09/26/2021

Contents

In this article, you will learn how to use the Ruby shift method.

Using the shift method

The shift method in Ruby is a useful method that can be used to remove and return the first element from an array or a queue-like object. The method modifies the original object, removing the first element, and shifting the rest of the elements one position to the left.

Basic usage

To use the shift method, you need to have an array or an object that supports the shift method. For example, consider the following array:

fruits = ["apple", "banana", "orange", "kiwi"]

To remove and return the first element of the fruits array, you can call the shift method as follows:

first_fruit = fruits.shift

This will remove the “apple” element from the fruits array, and assign it to the first_fruit variable.

Shift multiple elements

You can also use the shift method to remove multiple elements from the beginning of an array. To do this, you can pass an integer argument to the shift method, which specifies the number of elements to remove.

For example, consider the following array:

numbers = [1, 2, 3, 4, 5]

To remove the first three elements from the numbers array, you can call the shift method as follows:

first_three_numbers = numbers.shift(3)

This will remove the first three elements (1, 2, and 3) from the numbers array, and assign them to the first_three_numbers variable as an array.

Shift from a queue-like object

The shift method can also be used to remove and return the first element from a queue-like object, such as a Queue or a Deque in Ruby. These objects have a shift method that behaves the same way as the shift method of an array.

For example, consider the following Queue:

require 'thread'

queue = Queue.new
queue.push("apple")
queue.push("banana")
queue.push("orange")
queue.push("kiwi")

To remove and return the first element from the queue, you can call the shift method as follows:

This will remove the “apple” element from the queue, and assign it to the first_fruit variable.