Skip to content

Instantly share code, notes, and snippets.

@mehdi-farsi
Last active December 17, 2022 10:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mehdi-farsi/2729f421c0d408552cf22adab45a0ca8 to your computer and use it in GitHub Desktop.
Save mehdi-farsi/2729f421c0d408552cf22adab45a0ca8 to your computer and use it in GitHub Desktop.
class String
def palindrome?
tmp = self.downcase.gsub(/[^[[:alnum:]]]/, '') # you can also use /\W/ but it'll keep the underscores
tmp == tmp.reverse
end
end
"madam".palindrome? # => true
"racecar".palindrome? # => true
"madam, . ".palindrome? # => true
"02/02/2020".palindrome? # => true
"11/11/11 11:11".palindrome? # => true
"Madam, I'm Adam".palindrome? # => true
"A man, a plan, a canal – Panama".palindrome? # => true
@go2null
Copy link

go2null commented Sep 7, 2020

possible typo - the /i in the regex as you are already using downcase?

@mehdi-farsi
Copy link
Author

mehdi-farsi commented Sep 7, 2020

possible typo - the /i in the regex as you are already using downcase?

@go2null Indeed. Thank you! 😉

@go2null
Copy link

go2null commented Sep 9, 2020

👍

@lxbrito
Copy link

lxbrito commented Sep 11, 2020

There's no need to use strip at the end, the gsub is already removing the white spaces. And speaking of white spaces, should an empty string be considered a palindrome?

@mehdi-farsi
Copy link
Author

There's no need to use strip at the end, the gsub is already removing the white spaces. And speaking of white spaces, should an empty string be considered a palindrome?

Well done! 👍

The strip method call comes from my previous implementation. Thank you.
Uh.. It's a good question. I think that empty strings should be considered as palindrome. But it's subjective.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment