How to add an element to the end of an array using "<<" in Ruby

Overview

You can push elements in an array to the end of the array with the push() method or << operator. In this shot, we will learn how to use the << operator to add elements to an array.

The << operator pushes elements to the end of the array. This can be chained together, meaning that several elements can be added to the end of an array at the same time with the << operator.

Syntax

array << obj

Parameters

obj: The element to be appended to the array; obj can be a single element or an array.

Return value

The << operator returns the array itself with the appended elements.

Code example

In the code below, we demonstrate the use of the << operator. We append several elements to an array and display the returned values on the console.

# create Ruby arrays
array1 = [1, 2, 3, 4]
array2 = [["ab", "cd"], ["ef", "gh"]]
array3 = ["For", "While", "Do While"]
array4 = ["Google", "Netflix", "Amazon"]
# append elements to the
# arrays using the "<<" operator
a = array1 << 5
b = array2 << ["ij", "kl"]
c = array3 << "Switch Statement"
d = array4 << "Apple" << "Meta"
# display returned values to the console
puts "#{a}" # 5 is appended
puts "#{b}" # ["ij", "kl"] is appended
puts "#{c}" # "Switch Statement" is appended
puts "#{d}" # "Apple" and "Meta" are appended

In the code above, we see that several elements are appended to the arrays we created with the << operator.