Ruby push() Method

Ruby push() Function with Examples

Ruby push() method is a function that helps to push elements at the end of the array. You can push almost all kind of objects using the push method into an array.

For example, you can push another array at the end of an array. It will be pushed as a nested array. Other objects like string, double, integer, boolean, etc also can be pushed.

Ruby push() Method

Syntaxarr.push(elemnt1, elemnt2, ...)
Where arr is the array and the elements will be pushed at the end of the arr array.
Returns valueThe push() method returns the array with the pushed value at the end
ParametersElements to be pushed are parameters of this function

Example program:

arr1 = [12, 13, 14, 15]
arr1.push(16, 17)
puts "#{arr1}"

arr2 = ['a', 'b', 'c']
arr2.push('d', 'e')
puts "#{arr2}"

arr3 = ["Jhon", "Doe"]
arr3.push("Lisa")
puts "#{arr3}"

arr4 = []
arr4.push(1, 2, 3, 4)
puts "#{arr4}"

arr5 = [12, 43, 22]
arr5.push([44,41])
puts "#{arr5}"

arr6 = [9, 8, 7, 4]
newArr = 3, 1
arr6.push(newArr)
puts "#{arr6}"

arr7 = [19, 20, 21]
newArr = [22, 23, [24, 25]]
arr7.push(newArr)
puts "#{arr7}"

Output

[12, 13, 14, 15, 16, 17]
["a", "b", "c", "d", "e"]
["Jhon", "Doe", "Lisa"]
[1, 2, 3, 4]
[12, 43, 22, [44, 41]]
[9, 8, 7, 4, [3, 1]]
[19, 20, 21, [22, 23, [24, 25]]]

Note: All the pushing methods are shown in the above example. Write, run, modify, and run to explore yourself.

Posted in