Skip to main content

Ruby reverse array method

In ruby programming language the reverse method of the array returns a new array that includes the inverted sequence element of the given array. That syntax as follows.

// Or

It is an inbuilt method and does not require any other module for its use. let's take an example to understand working functionality.

# Given arrays (code,num)
code = ["C","C++","Java","Ruby","Swift","Python"]
num = [1,2,3]
# Apply reverse method
c = code.reverse()
n = num.reverse
# Display array elements
print(" code : ",code)
print("\n c    : ",c)
print("\n num  : ",num)
print("\n n    : ",n)
Ruby reverse array method example
 code : ["C", "C++", "Java", "Ruby", "Swift", "Python"]
 c    : ["Python", "Swift", "Ruby", "Java", "C++", "C"]
 num  : [1, 2, 3]
 n    : [3, 2, 1]

Note that this method is returning a new elements which contain reverse order element. If we want to change the actual array, assign the result of the reverse method to the actual array (variable name).

# Given array
record = ["me",nil,[1,4,3],9083]

# Display array element
print(" Before : ",record)

# Apply reverse method
record = record.reverse

# Display array element
print("\n After    : ",record)
Reverse actual array element
 Before : ["me", nil, [1, 4, 3], 9083]
 After    : [9083, [1, 4, 3], nil, "me"]

Note that the reverse() method changes the element order of a given array, if the elements inside it include other enumerable objects, then its internal elements are not modified.


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