Ruby unshift array method

In ruby programming language unshift() method are adding given objects at the beginning of array. Parameters of this method are optional, that is capable to accept single or multiple parameters. The syntax as follows.

 # Add single object
arr.unshift(object)

# Add multiple object
arr.unshift(object,object)

Ruby unshift() method example

unshift() are capable to add given parameter object at the beginning of array. Let's take few examples to add single and multiple elements by using unshift method.

# Our array
arr1 = [3,6,2,8]
arr2 = [true,false,[1,4,3]]

# Before unshift
print(" Array arr1 : ",arr1)
print("\n Array arr2 : ",arr2)

# unshift operation
# add new array
arr1.unshift([1,7,8])
# add single value
arr2.unshift(67)

# After unshift
print("\n Array arr1 : ",arr1)
print("\n Array arr2 : ",arr2)
Ruby unshift method example A
 Array arr1 : [3, 6, 2, 8]
 Array arr2 : [true, false, [1, 4, 3]]
 Array arr1 : [[1, 7, 8], 3, 6, 2, 8]
 Array arr2 : [67, true, false, [1, 4, 3]]

In the above example, a single element is added to existing array. This method can add more than one element by passing parameter values. For example.

# Example 2

# Our arrays
a1 = [1,2,3]
a2 = ["you","me"]

# Before unshift
print(" Array a1 : ",a1)
print("\n Array a2 : ",a2)

# unshift operation
# add multiple objects
a1.unshift(a2,"like")
a2.unshift(10,20,30)

# After unshift
print("\n Array a1 : ",a1)
print("\n Array a2 : ",a2)
Ruby unshift method example B
 Array a1 : [1, 2, 3]
 Array a2 : ["you", "me"]
 Array a1 : [[10, 20, 30, "you", "me"], "like", 1, 2, 3]
 Array a2 : [10, 20, 30, "you", "me"]

By default this method are return the reference of modified array. let see an example.

# Example 3

# Our array
arr = [1,2,3]

# Before unshift
print(" Array arr : ",arr)

# unshift operation
v = arr.unshift(true,false)

# After unshift
print("\n Array arr : ",arr)
print("\n  v : ",v)
Ruby unshift method example C
 Array arr : [1, 2, 3]
 Array arr : [true, false, 1, 2, 3]
  v : [true, false, 1, 2, 3]


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