Array push(), pop() and clear() functions in Ruby


The most widely used functions in Ruby when it comes to arrays are push(), pop(), and clear() functions. These functions are used when we want to enter, take out and clear the array data, respectively. In this article, we will learn about all these functions one by one.

push() Function

The push function in Ruby is used to push elements at the end of an array. The function can accept single as well as multiple objects as arguments.

Consider the code shown below as reference of the push() function.

Example 1

# push() function example in Ruby

# few arrays
first_arr = ["Letters", "a", "b"]
second_arr = ["Words", "tuts", "Tuts"]
third_arr = ["Cities", "Noida", "Bangalore"]

# push() function
res_a = first_arr.push("c","d")
res_b = second_arr.push("Tut", "TutorialsPoint")
res_c = third_arr.push("Delhi", "Bangkok")

# printing result of push function
puts "#{res_a}"
puts "#{res_b}"
puts "#{res_c}"

Output

["Letters", "a", "b", "c", "d"]
["Words", "tuts", "Tuts", "Tut", "TutorialsPoint"]
["Cities", "Noida", "Bangalore", "Delhi", "Bangkok"]

pop() Function

The pop function is used when we want to remove elements from the array. It takes an integer as an argument and the integers denote how many elements we want to remove from the array.

Consider the example shown below as reference to the same.

Example 2

# pop() function example in Ruby

# few arrays
first_arr = ["Letters", "a", "b"]
second_arr = ["Words", "tuts", "Tuts","Tut", "TutorialsPoint"]

# pop() function
res_a = first_arr.pop
res_b = second_arr.pop(1)
res_c = second_arr.pop(2)

# printing result of pop function
puts "#{res_a}"
puts "#{res_b}"
puts "#{res_c}"

Output

b
["TutorialsPoint"]
["Tuts", "Tut"]

clear() Function

The clear function is used to remove all the elements of the given array and returns the array with no elements.

Example 3

Consider the code shown below

# clear() function example in Ruby

# few arrays
first_arr = ["Letters", "a", "b", "c", "d"]
second_arr = ["Words", "tuts", "Tuts", "Tut", "TutorialsPoint"]
third_arr = ["Cities", "Noida", "Bangalore", "Delhi", "Bangkok"]

# clear() function
res_a = first_arr.clear
res_b = second_arr.clear
res_c = third_arr.clear
# printing result of clear function

puts "#{res_a}"
puts "#{res_b}"
puts "#{res_c}"

Output

[]
[]
[]

Updated on: 25-Jan-2022

771 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements