- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Array reverse() vs reverse! in Ruby
In this article, we will explore the two most widely used methods on arrays in Ruby. These are the reverse() method and the reverse! method.
reverse() method
The reverse() method in Ruby reverses the content of the array and returns a new array. Now, let's take a couple of examples to understand how it works.
Example 1
# reverse() method in Ruby # array declaration first_arr = [18, 22, 33, nil, 7, 6] # array declaration second_arr = [1, 5, 1, 3, 88, 9] # array declaration third_arr = [18, 22, 55, 6] # reverse method example puts "reversed array : #{first_arr.reverse()}
" puts "reversed array : #{second_arr.reverse()}
" puts "reversed array : #{third_arr.reverse()}
"
Output
reversed array : [6, 7, nil, 33, 22, 18] reversed array : [9, 88, 3, 1, 5, 1] reversed array : [6, 55, 22, 18]
Example 2
Let's explore one more example of the same reverse method.
# reverse() method in Ruby # array declaration first_arr = ["abc", "nil", "dog"] # array declaration second_arr = ["buffalo", nil] # array declaration third_arr = ["snake", nil, "dog"] # reverse method example puts "reversed array : #{first_arr.reverse()}
" puts "reversed array : #{second_arr.reverse()}
" puts "reversed array : #{third_arr.reverse()}
"
Output
reversed array : ["dog", "nil", "abc"] reversed array : [nil, "buffalo"] reversed array : ["dog", nil, "snake"]
reverse! Function
The reverse! function is used when we want to reverse the input array content into the same array. Let's explore an example of the reverse! function.
Example 3
# arrays of elements arr1 = ["a", "b", "c", "d"] arr2 = [] arr3 = [1] arr4 = ["Javed", "Raju","Pruthvi"] # reverse! A = arr1.reverse! B = arr2.reverse! C = arr3.reverse! D = arr4.reverse! # Printing the same input array # with reversed elements puts "#{A}" puts "#{B}" puts "#{C}" puts "#{D}"
Output
["d", "c", "b", "a"] [] [1] ["Pruthvi", "Raju", "Javed"]
- Related Articles
- String reverse vs reverse! function in Ruby
- Poison Reverse vs Split Horizon
- Array reverse() in JavaScript
- JavaScript Array reverse()
- Reverse array field in MongoDB?
- Reverse an array in C++
- Reverse sum array JavaScript
- Reverse an array using C#
- Java program to reverse an array
- C# program to reverse an array
- Reverse array with for loops JavaScript
- Reverse index value sum of array in JavaScript
- Reverse Subarray To Maximize Array Value in C++
- How I can reverse a Java Array?
- Solution for array reverse algorithm problem JavaScript

Advertisements