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).

First solution

def is_palindrome?(str)
  reversed = str.split('').reverse.join
  str === reversed

We begin by creating a reversed string which consists of the following steps:

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 split, reverse, and 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

Third solution (extend String class)

An alternative (perhaps more elegant) solution would be to extend Ruby’s String class.

class String
  def palindrome?
    self === self.reverse

We can then call the palindrome? method directly on any string.

'anna'.palindrome? # true
'jim'.palindrome? #false

Isn’t Ruby wonderful?

Sajad Torkamani

Hello! My name is Sajad. I’m a software developer at Nationwide and an aspiring entrepreneur. Originally from Afghanistan, I moved to London at an early age and have been living here for the past 20 years.

This is my personal website where I blog mostly about programming with occasional thoughts on a bunch of other things. I write mainly for my own benefit as I find that writing helps clarify my otherwise very confused thoughts.

Get in touch: