The .push
method of an array in Ruby adds an element to the end of an array. When it is done, it returns the array itself with the pushed elements.
array.push([element])
[element]
: This could be one or more elements to be added at the end of the given array.The push()
method returns the array of the pushed element.
In the example below, we will create some arrays. Then later, we use the push()
method to add other elements to these arrays and print the arrays to the console.
# Initializing some arrays of elementsArray1 = [1, 2, 3]Array2 = ["a", "b", "c"]Array3 = ["Javascript", "Python", "C++"]# Using the push() methodA = Array1.push(4,5)B = Array2.push("d", "e")C = Array3.push("Ruby", "Java")# Print array of pushed elementsputs "#{A}"puts "#{B}"puts "#{C}"