How to Use the Ruby push Method

09/22/2021

Contents

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

Using the push method

The push method is a common method used in Ruby for adding elements to an existing array. This method can be used to add a single element to an array or multiple elements at once.

Syntax

Here is the basic syntax for using the push method:

array_name.push(element1, element2, ...)
Examples
Adding a Single Element to an Array

To add a single element to an array, you can use the push method like this:

my_array = [1, 2, 3]
my_array.push(4)

In this example, the push method is used to add the number 4 to the end of the my_array array. After running this code, the my_array array will look like this:

[1, 2, 3, 4]
Adding Multiple Elements to an Array

You can also use the push method to add multiple elements to an array at once. To do this, simply list the elements you want to add as arguments to the push method, separated by commas. Here is an example:

my_array = [1, 2, 3]
my_array.push(4, 5, 6)

In this example, the push method is used to add the numbers 4, 5, and 6 to the end of the my_array array. After running this code, the my_array array will look like this:

[1, 2, 3, 4, 5, 6]
The Shovel Operator (<<)

In addition to the push method, Ruby also provides a shorthand operator for adding elements to an array: the shovel operator (<<). Here's an example:

my_array = [1, 2, 3]
my_array << 4

In this example, the shovel operator is used to add the number 4 to the end of the my_array array. After running this code, the my_array array will look like this:

[1, 2, 3, 4]