Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

ruby
communitycreator

How to use array.push() in Ruby?

okwudili onyejiaku

array.push() is a Ruby array method that is used to add elements at the end of an array. This method returns the array itself.

One important aspect of this is that this method can be chained.

Syntax

array.push(obj, ...)

Parameters

obj: This is the array or element values that you want to push to the end of an array.

Return value

The value returned is the same array with the elements appended to its end.

Example

In the example below, we create arrays, append some elements to them, and print their returned values to the console.

# create arrays
array1 = [1, 2, 3, 4, 5]
array2 = ["Ruby", "Javascript", "Python"]
array3 = ["a", "b", "c", "d", "e", "f", "g"]
array4 = [["dog", "cat", "rat"], "human", "stars", ["fish", "meat"]]
array5 = [nil]

# append elements to the arrays
a = array1.push(6, 7, 8, 9, 10)
b = array2.push("Python", ["C", "C++", "Java"], "Kotlin")
c = array3.push(["h", "i", "j"], ["k", "l", "m"])
d = array4.push("plants", "rocks")
e = array5.push("nil");

# print appended arrays to console
puts "#{a}"
puts "#{b}"
puts "#{c}"
puts "#{d}"
puts "#{e}"

Note: The push() method can be chained.

Take a look at the example below, which chains the push() method:

# create an array
array = [1, 2, 3]

# chain push method
array.push(["a", "b", "d"])
     .push(["Ruby", "Java", "C"])
     .push(["Nigeria", "Egypt", "USA"])

# print array
puts "appended array = #{array}"

RELATED TAGS

ruby
communitycreator
RELATED COURSES

View all Courses

Keep Exploring