I am having trouble with getting my for-loop to process a string. It's just a simple method to tell whether or not a word is a palindrome (a word that is spelled that same way backwards and forwards). I have tweaked the for-loop multiple times but keep getting the same error message below. Could anyone point me in the right direction?
Code:
def palindrome?(string)
string2 = ""
for i in string
string2 = string[i] + string2
end
if string2 == string1
return true
end
end
palindrome?("abcba")
Error:
hours.rb:7:in `palindrome?': undefined method `each' for 5:Fixnum (NoMethodError)
from hours.rb:17:in `<main>'
what you're looking for is:
def palindrome?(string)
string2 = ""
for i in 0...string.length
string2 = string[i] + string2
end
if string2 == string
return true
end
end
Note you could define it simpler:
def palindrome?(string)
string == string.reverse
end