How to append multiple elements and arrays to an array in Ruby

Appending or pushing arrays, elements, or objects to an array is easy. This can be done using the << operator, which pushes elements or objects to the end of the array you want to append to. The magic of using << is that it can be chained.

Syntax

array << object

Parameter

object: This could be an element or an array. You can append as many as you want.

Return value

A new array is returned, which is the original array and the appended elements.

Code example

In the example below, we create arrays and append some elements or arrays to them. We also chain appends and print the returned values to the console.

# creare arrays
languagesArray = ["Java", "C++", "Python", "Javascript", "Ruby on Rails!" ]
numbersArray = [1, 2, 3, 4, 5]
alphabetsArray = ["a", "b", "c", "d", "e"]
booleanArray = [true, false]
animalsArray = ["dog", "cat", "rat", "cow", "bat"]
# append elements to these arrays
a = languagesArray << "C" # One append
b = numbersArray << 6 << 7 << 8 # Chianed elements
c = alphabetsArray << "f" << "g" << ["a", "e", "i", "o", "u"]
d = booleanArray << false << true
e = animalsArray << ["lion", "tiger", "wolf"] << "goat"
# print values to the console
puts "#{a}"
puts "#{b}"
puts "#{c}"
puts "#{d}"
puts "#{e}"

In the code above, we created several arrays and appended some items to then. In line 9, only one element was appended to the languagesArray. From line 10 to line 13, we then chained the appends.

Free Resources