3
\$\begingroup\$

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")
\$\endgroup\$
5
\$\begingroup\$

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
\$\endgroup\$
2
\$\begingroup\$

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.

\$\endgroup\$
1
\$\begingroup\$

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.

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.