sajad torkamani

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

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?

Tagged: Ruby