我正在用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
===============================================

第一个输出应该是“false”,我不明白它为什么不返回这个值。它确实会打印“string is not a palindrome”,因此我希望它也将“is_palindrome”变量设置为“false”并返回该值。

最佳答案

就您的解决方案而言,我认为您误解了您的代码按预期工作当然false == false是真的,所以palindrome?("abc') == false is true
虽然与您的解决方案没有直接关系,但是如何使用ruby的内置功能呢

def palindrome?(string):
    string == string.reverse
end

08-18 15:23
查看更多