我正在Ruby中进行编程练习以确定字符串是否是回文。以下是我想出了:确定字符串是否为回文的Ruby编程练习
# Write a method that takes a string and returns true if it is a
# palindrome. A palindrome is a string that is the same whether written
# backward or forward. Assume that there are no spaces; only lowercase
# letters will be given.
#
# Difficulty: easy.
def palindrome?(string)
iterations=string.length/2
is_palindrome=true
i=0
while i<iterations
if string[i] != string[string.length-i-1]
puts("string is not a palindrome")
is_palindrome=false
end
i+=1
end
return is_palindrome
end
# These are tests to check that your code is working. After writing
# your solution, they should all print true.
puts("\nTests for #palindrome?")
puts("===============================================")
puts('palindrome?("abc") == false: ' + (palindrome?('abc') == false).to_s)
puts('palindrome?("abcba") == true: ' + (palindrome?('abcba') == true).to_s)
puts('palindrome?("z") == true: ' + (palindrome?('z') == true).to_s)
puts("===============================================")
这将返回以下:
Tests for #palindrome?
===============================================
string is not a palindrome
palindrome?("abc") == false: true
palindrome?("abcba") == true: true
palindrome?("z") == true: true
===============================================
第一输出应该是“假的”,我想不通为什么它没有返回这一点。它确实打印出“字符串不是回文”,所以我希望它也会将“is_palindrome”变量设置为“false”并返回。
嗨hspandher,谢谢你的回复。事实上,我相信我误解了结果;如果代码全部返回“true”,代码实际上也可以工作。 (是的,使用.reverse给出了相同的结果)。 –