sajad torkamani

What is a palindrome?

A palindrome is a sequence of characters that reads the same backwards or forwards. Examples include annabob, or madam.

Let's look at a couple of solutions to checking for a palindrome.

First solution

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

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 splitreverse, 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?

Tagged: Ruby