This code returns true if the sentence is a palindrome, and false otherwise. Is there a better way of doing this?
def palindrome?(sentence)
array_stripped_sentence = sentence.reverse.downcase.delete('').split('')
array_stripped_sentence == sentence.downcase.delete(' ').split('')
end
puts palindrome?("Never odd or even")
3 Answers 3
You can call reverse
on String
directly.
While it doesn't particularly apply here, instead of split
ting on ''
, you should use the method chars
.
Who says you'll be passing a sentence? Does this method not work for single words? If I call palindrome? 'radar'
will I get an error?
I'd recommend using tr
to strip out all non-alphabetic characters, instead of just delete
ing spaces.
def palindrome?(testing)
stripped = testing.downcase.tr('^a-z', '')
stripped.reverse == stripped
end
I am not Ruby developer, so I cannot help you with conventions or if there are short methods.. (It also means that someone aware of these things should edit the answer)
But here is a an improvement which worked for me in online compiler I tried:
def palindrome?(sentence)
array_stripped_sentence = sentence.downcase.delete(' ').split('')
array_stripped_sentence == array_stripped_sentence.reverse()
end
puts palindrome?("Never odd or even")
Main improvement I could see in your code was that you were chaining same methods multiple times, when there was no need.
**
Other improvements:
What if your string contains characters other Alphanumeric characters and space? For example,
Never odd or even!
How do you process them? [Hint: Regular expressions]If you need to strip away special characters regularly, and not just in palindrome program, it might be better to make a separate function for it.
To get this to work reliably with all the possible whitespace characters, a simple change will suffice:
def palindrome?(sentence)
letters = sentence.gsub(/[[:space:]]/, '').downcase
letters == letters.reverse
end
[[:space:]]
matches all unicode whitespace, including tabs, returns, non-breaking spaces and other wacky anomolies.
So, for instance, now this works:
puts palindrome?("ÑévëR \u00A0\u2002ødd ør \tëvéÑ\n\r\t ") # => true
However, the following won't work, because String#downcase
only works with ASCII:
puts palindrome?("ÑévëR ødd ør \tëvéñ\n\r\t ") # => false
Neither will the following, because the accented chars won't match:
puts palindrome?("Never odd ør \tëvén\n\r\t ") # => false
If you need to accurately convert accented characters to their root letters, you would need to use something like ActiveSupport's Multibyte Chars.