Ruby shift array method

In ruby programming language, shift() array method is used to remove single and multiple elements at beginning of array. By default this method are remove single element which is exist in array. Syntax of this method as follows.

Syntax Array.shift(),Array.shift
Parameter None
Return Single element, Or nil

In above syntax are based on empty parameter (no parameter). So this method return only one value. When array is empty then they returned a nil value. Otherwise they returning a removed element. Another syntax of this method as follows.

Syntax Array.shift(n)
Parameter Number of element
Return Return array, empty array

This method takes a parameter value that indicates the number of elements to be removed. When provide parameter value is always return an array, Which contains removing elements. When array is empty so its returns an empty array.

Both types (Array.take, Array.take(n)) of this method modify the value (array) of the actual array.

Ruby shift method example

Let's take a simple example which is removing an element.

# Example shift() single element

# Our arrays
record = [1,2,3,4]
data = [[1,2],10,20]

# Before shift
print(" Before shift")
print("\n record : ", record)
print("\n data : ", data)

# Shift operation
v1 = record.shift
v2 = record.shift()
v3 = data.shift()

# After shift
print("\n After shift")
print("\n record : ", record)
print("\n data : ", data)
Ruby shift method example 1
 Before shift
 record : [1, 2, 3, 4]
 data : [[1, 2], 10, 20]
 After shift
 record : [3, 4]
 data : [10, 20]

Note that the shift method returns the removed element and reset the index of actual array after the deletion. Other example which is remove the multiple elements.

# Example 2

# Our array
record = [1,[true,false],2,3,4]

# Before shift
print(" Before shift")
print("\n record : ", record)

# Shift operation
v = record.shift(3)

# After shift
print("\n After shift")
print("\n record : ", record)
print("\n v : ", v)
Ruby shift method example 2
Before shift
 record : [1, [true, false], 2, 3, 4]
 After shift
 record : [3, 4]
 v : [1, [true, false], 2]

Some other example which is based on default behaviour of this method.

# Example 3

# Our arrays
record = []
data = [1,2]

# Before shift
print(" Before shift")
print("\n record : ", record)
print("\n data : ", record)

# Shift operation
v1 = record.shift  
v2 = data.shift(4) 

# After shift
print("\n After shift")
print("\n record : ", record)  # []
print("\n v1 : ", v1)          # nil
print("\n v2 : ", v2)          # [1,2]
 Before shift
 record : []
 data : []
 After shift
 record : []
 v1 : 
 v2 : [1, 2]


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







© 2021, kalkicode.com, All rights reserved