Home »
Ruby »
Ruby Programs
Ruby program to reverse an array without using library function
Ruby Example: Write a program to reverse an array without using library function.
Submitted by Nidhi, on January 19, 2022
Problem Solution:
In this program, we will create an array of integer elements. Then we will reverse the array elements and assign them to another array.
Program/Source Code:
The source code to reverse an array without using the library function is given below. The given program is compiled and executed successfully.
# Ruby program to reverse an array without
# using library function
arr = [12,45,23,39,38];
RevArray = Array.new(arr.size());
count1 = 0;
count2 = arr.size()-1;
while(count1<arr.size())
RevArray[count1]=arr[count2];
count1=count1 + 1;
count2=count2 - 1;
end
print "Array:\n";
count1=0;
while(count1<arr.size)
print arr[count1]," ";
count1=count1 + 1;
end
print "\nReversed Array:\n";
count1=0;
while(count1<RevArray.size)
print RevArray[count1]," ";
count1=count1 + 1;
end
Output:
Array:
12 45 23 39 38
Reversed Array:
38 39 23 45 12
Explanation:
In the above program, we created an array of integer elements. Then we reversed the array elements and assigned them to the RevArray. After that, we printed the original and reversed the array.
Ruby Arrays Programs »