Skip to main content

Ruby push array method

In ruby programming language the push() method of the array are used to add single and multiple object at the end of array. The number of parameters of this method depends on the insertion of the elements. Its syntax is as follows.

array.push(value) // Add single element
array.push(n1,n2,n3,..) // Add multiple element

This is the inbuilt method and the parameter value is optional, when no value is provided it does not modify the element of the array. And upon providing the element, it updates the element of the array.

Ruby push method example

Lets we take an empty array and adding some objects using of push() method at the end of array.

# Empty array
record = []

print(" Initially : ",record)

# Add a element
record.push(10)

print("\n When push ",10 ," : ",record)

# Add other element
record.push(67)

print("\n When push ",67 ," : ",record)


# Add other element
record.push(12)

print("\n When push ",12 ," : ",record)
Ruby push method example 1
 Initially : []
 When push 10 : [10]
 When push 67 : [10, 67]
 When push 12 : [10, 67, 12]

In the above example, a single element is adding at a time, we can add more than one element using push() method in the following ways.

# Array element
alphabet = ['a','z']
record = [1,2]

# Display initial value
print(" record ",record)

# Add (10,20)
record.push(10,20)
print("\n record ",record)

# Add array
record.push([false,true])
print("\n record ",record)

# Add array object
record.push(alphabet)
print("\n record ",record)

# Add new hash 
record.push({"id"=>"oo7"})
print("\n record ",record)
Ruby push multiple element
 record [1, 2]
 record [1, 2, 10, 20]
 record [1, 2, 10, 20, [false, true]]
 record [1, 2, 10, 20, [false, true], ["a", "z"]]
 record [1, 2, 10, 20, [false, true], ["a", "z"], {"id"=>"oo7"}]

Observe in the above example when an existing object is pushed into the array. Then the reference to the given object is specified to array.





Comment

Please share your knowledge to improve code and content standard. Also submit your doubts, and test case. We improve by your feedback. We will try to resolve your query as soon as possible.

New Comment