Home
Ruby
reverse (String, Array)
Updated Sep 17, 2024
Dot Net Perls
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.
String 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
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 pages with code examples, which are updated to stay current. Programming is an art, and it can be learned from examples.
Donate to this site to help offset the costs of running the server. Sites like this will cease to exist if there is no financial support for them.
Sam Allen is passionate about computer languages, and he maintains 100% of the material available on this website. He hopes it makes the world a nicer place.
This page was last updated on Sep 17, 2024 (edit).
Home
Changes
© 2007-2025 Sam Allen