Learning Ruby, currently doing the palindrome method creator on Ruby Monk.
Basically, write a method that returns true if a string is indeed a palindrome.
This is my code.
def palindrome?(sentence)
sentence.downcase!
array_1 = sentence.split("")
array_2 = sentence.reverse.split("")
if array_1 == array_2
true
else
false
end
end
p palindrome?("NeverOddOrEven")
It works, but only if there are no spaces between each word.
So if you check "Never Odd Or Even" (as opposed to "NeverOddOrEven") it fails.
How should I fix this?
Thanks!
Add:
sentence.gsub!/\W/, ''
just after sentence.downcase!
Also note, that your method has a side effect:
string = 'NeverOddOrEven'
p palindrome?(string) #=> true
p string #=> neveroddoreven
To fix this, change first two lines to:
sentence = sentence.downcase.gsub /\W/, ''