Log in
updated 11:29 AM UTC, May 4, 2016

Ruby program to check if String is a palindrome

  • Written by Madhu V Rao
  • Published in Ruby

Definition of Palindrome:

 A word, phrase, verse, or sentence that reads the same backward or forward. For example:

A man, a plan, a canal, Panama! 
Malayalam
Glenelg 

  Ruby provides easy way to check if a String is a Palindrome. Below lines of code is all that is needed to check if String is a palindrome. lets go through it:

def palindrome?(str)
  onlyLetters = str.downcase.scan(/\w/)
  onlyLetters == onlyLetters.reverse
end

This function just ignores the case (str.downcase) and takes only letters from the string (.scan(/\w/)).

str.scan(/\w/) uses regular expression to select only the letters.

once it is done , its easy to reverese and check if the value is equal to the string. Perhaps the shortest code to do it this efficiently.

 


Powered by Bullraider.com
Follow Us on Twitter
Find Us on Facebook
Follow Us on Google
Follow Us on Pinterest