patternrubyMinor
Palindrome Validator
Viewed 0 times
palindromevalidatorstackoverflow
Problem
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")Solution
You can call
While it doesn't particularly apply here, instead of
Who says you'll be passing a sentence? Does this method not work for single words? If I call
I'd recommend using
reverse on String directly.While it doesn't particularly apply here, instead of
splitting 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 deleteing spaces.def palindrome?(testing)
stripped = testing.downcase.tr('^a-z', '')
stripped.reverse == stripped
endCode Snippets
def palindrome?(testing)
stripped = testing.downcase.tr('^a-z', '')
stripped.reverse == stripped
endContext
StackExchange Code Review Q#101332, answer score: 5
Revisions (0)
No revisions yet.