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).
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.
reverse()
call.value = "rat" # Reverse in-place. # ... Without an exclamation, reverse returns a new string. value.reverse! puts valuetar
Reverse
arrayA 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
, 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 resultCAT TCA
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.