gpt4 book ai didi

ruby - 如何写回文支票?

转载 作者:数据小太阳 更新时间:2023-10-29 08:48:16 25 4
gpt4 key购买 nike

我目前正在通过一些程序来学习 Ruby。我一直在研究回文程序,但无论输入(回文)如何,我最终都会在 else 上结束。

这是我一直在尝试的一些代码:

print "enter a string:\n"
string = gets
if string.reverse == string
print "it's a palindrome"
else
print "not a palindrome.\n"
end

非常感谢任何帮助/建议。

最佳答案

换行符没有从字符串中删除。试试这个代码:

print "enter a string:\n"
string = gets.chomp
if string.reverse == string
print "it's a palindrome"
else
print "not a palindrome.\n"
end

这里有一些解释:

>> string = gets
racecar # input string
=> "racecar\n"
>> "racecar\n" == "racecar\n".reverse # "racecar\n" is not a palindrome with newline character
=> false
>> string = gets.chomp # chomp method deletes newline character
racecar
=> "racecar"
>> "racecar" == "racecar".reverse # "racecar" without a newline character is a palindrome
=> true

关于ruby - 如何写回文支票?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20794104/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com