Home » Ruby programming

Ruby pop() function

Ruby pop() function: Here, we are going to learn about the pop() function with example in Ruby programming language.
Submitted by Hrithik Chandra Prasad, on September 01, 2019

pop() function in Ruby

If you are aware of the logic to create pop() function used in the data structure, then you are ready to understand the internal logic of pop() function which is already defined in Ruby’s library. The pop () function is used to delete or pop out the element from the stack. Likewise in Ruby also, the pop() function is used to pop out or delete the element from the stack.

The return type of pop() function is an array and it returns an array in which it is invoked along with the popped elements.

Syntax:

 pop(Elements)

Now let us go through the implementation of pop() function with the help of examples.

pop() function only accepts integer value. The value you specify as the argument is the number of elements which are to be popped from the end of the array. If you invoke pop() without an argument, then the end most element will be popped out implicitly.

Example 1:

=begin
Ruby program to demonstrate pop() function.
=end

# Initializing arrays
Arr1 = [11, 12, 13, 14] 
Arr2 = ["x", "y", "z"] 
Arr3 = ["Includehelp", "C#", "Ruby"]
Arr4 = ["Kiwi","Banana","Orange","Papaya"] 
   
# Invoking pop() function with elements to be popped 
Arr1pop = Arr1.pop(1)                 
Arr2pop = Arr2.pop(1)                
Arr3pop = Arr3.pop(2)
Arr4pop = Arr4.pop(2)   
   
# Printing the array of storing popped element 
puts "#{Arr1pop}"
puts "#{Arr2pop}"
puts "#{Arr3pop}"
puts "#{Arr4pop}"

Output

[14]
["z"]
["C#", "Ruby"]
["Orange", "Papaya"]

Code logic:

We have created four arrays. We are calling the pop() function with different arrays which is returning the popped elements in the corresponding new array. You can see the reflection of all popped elements in the new array.

Example 2:

=begin
Ruby program to demonstrate pop() function.
=end

# Initializing arrays
Arr1 = [11, 12, 13, 14,15,16,17,18,19,20,21,22,23,24,25,26] 
   
# Invoking pop() function with the number of elements to be popped 
puts "#{Arr1.pop}"
puts "#{Arr1.pop(1)}"
puts "#{Arr1.pop(2)}"
puts "#{Arr1.pop(3)}"
puts "#{Arr1.pop(4)}"
puts "#{Arr1.pop(5)}"

#printing final array after popping elements
puts "#{Arr1}"

Output

26
[25]
[23, 24]
[20, 21, 22]
[16, 17, 18, 19]
[11, 12, 13, 14, 15]
[]

Code logic:

In the above example, we are invoking pop() function multiple times in the same array. It is removing elements with every calling of the function. You can observe that when we invoke the pop() function with no arguments, it is popping out the last element of the array. When you specify the number of elements to be popped out, it pops out the element from the last up to the index number specified.



Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.