Skip to content

Instantly share code, notes, and snippets.

@mehdi-farsi
Last active December 17, 2022 10:40
Show Gist options
  • 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
@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