Ad space (banner)
๐Ÿ’ŽRuby Lessons
Lesson 43 / 68

Reversing a String and Checking for Palindromes

In this lesson you will learn to reverse a string with Ruby's reverse method and check for palindromes. This is for anyone searching for "Ruby reverse string".

.reverse reverses a string. A string that reads the same forwards and backwards is called a palindrome. Being able to call reverse straight on a string, without first breaking it into an array as some languages require, is a real convenience.

The sample code compares the original with its reverse in the single line str == str.reverse inside the palindrome? method. "racecar" comes out the same either way, so it is reported as a palindrome.

A common stumbling block for beginners coming from a language such as JavaScript is assuming they must convert the string to an array first. Ruby string handling is designed to cope naturally with multi-byte characters too, so calling reverse directly is enough.

Treating a string as a sequence of characters applies broadly to other text processing. Palindrome checking is a classic exercise that shows off just how easy Ruby makes this.

๐Ÿ“– Reference code
โœ๏ธ Your code
Type your code, then press "Run"

๐Ÿงช This site can't compile or run Ruby directly, so it checks on the spot whether what you typed matches the reference code (scoring happens entirely in your browser โ€” nothing is sent anywhere).

Ad space (banner)
Ad space (in-article)