2016-04-09 32 views
1

我正在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”并返回。

回答

3

就您的解决方案而言,我认为您错误地使您的代码正常工作。当然false == false是真的,所以palindrome?("abc') == false is true

虽然不直接关系到你的解决方案,但如何如何使用红宝石内置reverse功能

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

嗨hspandher,谢谢你的回复。事实上,我相信我误解了结果;如果代码全部返回“true”,代码实际上也可以工作。 (是的,使用.reverse给出了相同的结果)。 –

0

免责声明:这个答案不回答你的问题,other answer也较快。

如果你想测试你的代码,你还应该使用单元测试。

一个例子:

# 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. 
require 'minitest/autorun' 
class FirstLetterTest < Minitest::Test 
    def test_abc 
    refute(palindrome?('abc'), "'abc' is detected as a palindrome, but it isn't") 
    end 
    def test_abcba 
    assert(palindrome?('abcba'), "'abcba' is not detected as a palindrome") 
    end 
    def test_z 
    assert(palindrome?('z'), "'z' is detected as a palindrome, but it isn't") 
    end 
end 

我删除了你的puts("string is not a palindrome") - 它混淆输出。