How to Reverse a String in Ruby: Simple Syntax and Examples
In Ruby, you can reverse a string by calling the
reverse method on it, like "hello".reverse. This returns a new string with characters in reverse order.Syntax
The basic syntax to reverse a string in Ruby is using the reverse method on a string object.
string.reverse: Returns a new string with characters reversed.
ruby
"your_string".reverseExample
This example shows how to reverse the string "hello" and print the reversed string.
ruby
str = "hello" reversed_str = str.reverse puts reversed_str
Output
olleh
Common Pitfalls
One common mistake is trying to reverse the string in place using reverse without assignment, which does not change the original string. Use reverse! if you want to modify the string itself.
Also, calling reverse on nil will cause an error.
ruby
# Wrong way: does not change original string str = "hello" str.reverse puts str # prints "hello" # Right way: assign reversed string str = "hello" str = str.reverse puts str # prints "olleh" # Or use reverse! to modify in place str = "hello" str.reverse! puts str # prints "olleh"
Output
hello
olleh
olleh
Quick Reference
Summary tips for reversing strings in Ruby:
- Use
string.reverseto get a reversed copy. - Use
string.reverse!to reverse the string in place. - Remember
reversereturns a new string; original stays unchanged unless you assign or usereverse!.
Key Takeaways
Use the built-in
reverse method to reverse strings in Ruby easily.reverse returns a new reversed string without changing the original.Use
reverse! to reverse the string in place if needed.Always assign the result of
reverse if you want to keep the reversed string.Avoid calling
reverse on nil to prevent errors.