Home
Search
reverse (String, Array)Reverse the characters in a string, or elements in an array, with the reverse method.
Ruby
This page was last reviewed on Dec 9, 2022.
Reverse. This method inverts the order of characters in a string. This method is rarely useful, but helps when a string has characters that are a form of data (not text).
Array
Method notes. Reversing strings is sometimes helpful, like for creating a unique key from a string. And reverse() eliminates the burden of implementing the logic.
Reverse string. Here we see an example string—the string "rat" is reversed and this leaves us with the string "tar." We use an exclamation mark to change the variable we are using.
Info If we omit the exclamation mark, we would need to assign the "value" to the result of the reverse() call.
value = "rat" # Reverse in-place. # ... Without an exclamation, reverse returns a new string. value.reverse! puts value
tar
Reverse array. A string's letters cannot be directly sorted. But we can convert the string to an array (with split) and sort that. We can then reverse the array returned by sort.
Split
Sort
Tip This example reverses an array, not a string, because we converted the string to an array before reversing it.
letters = "cat" puts letters # Get letters from string with split. # ... Then sort, and reverse, the letters. # ... Finally join them back together into a string. result = letters.split("").sort.reverse.join() puts result
cat tca
A summary. In sorting, we can sometimes apply a descending (high-to-low) sort instead of invoking reverse(). But if we are not sorting, reverse() can be directly called.
Dot Net Perls is a collection of tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
No updates found for this page.
Home
Changes
© 2007-2023 Sam Allen.