How to check for palindromes in Ruby
A palindrome is a sequence of characters that reads the same backwards or forwards (e.g. anna, bob, madam).
def is_palindrome?(str) reversed = str.split('').reverse.join str === reversed end
We begin by creating a
reversed string which consists of the following steps:
- Split the string into array of characters
- Reverse the array of characters
- Join the reversed array so that we get a whole string again
These steps give us the reversed version of the original string so that we can then compare the original string (
str) to the reversed string (
reversed). If they are the same, the string is a palindrome.
Second solution (refactored)
The first solution should look very similar in almost any programming language as
join are very common methods.
However, since we are dealing with Ruby, we can use a more concise solution by using the String#reverse method.
def is_palindrome?(str) str === str.reverse end
Third solution (extend
An alternative (perhaps more elegant) solution would be to extend Ruby’s
class String def palindrome? self === self.reverse end end
We can then call the
palindrome? method directly on any string.
'anna'.palindrome? # true 'jim'.palindrome? #false
Isn’t Ruby wonderful?