HiveBrain v1.2.0
Get Started
← Back to all entries
patternrubyMinor

Palindrome Validator

Submitted by: @import:stackexchange-codereview··
0
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 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
end

Code Snippets

def palindrome?(testing)
  stripped = testing.downcase.tr('^a-z', '')
  stripped.reverse == stripped
end

Context

StackExchange Code Review Q#101332, answer score: 5

Revisions (0)

No revisions yet.