What is a palindrome?
A palindrome is a sequence of characters that reads the same backwards or forwards. Examples include
Let's look at a couple of solutions to checking for a palindrome.
def is_palindrome?(str) reversed = str.split('').reverse.join str === reversed end
We begin by creating a
reversed string by doing the following:
- Split the input string into an array of characters
- Reverse the array of characters
- Join the reversed array so that we get a whole string again
Once we have the reversed string, we can compare it to the original string (
str). If they are the same, the string is a palindrome, yay!
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
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?