什么';我的回文程序怎么了?(Ruby,用户自己输入字符串)

什么';我的回文程序怎么了?(Ruby,用户自己输入字符串),ruby,palindrome,Ruby,Palindrome,我决定制作一个回文程序,但我是通过检查用户输入的字符串来实现的。为了做到这一点,我想去掉大写字母、空格和标点符号。除了标点符号部分外,我设法让所有的东西都工作了。每次我尝试使用“夫人,我是亚当”这样的字符串时,程序就会崩溃。我对Ruby很陌生,我只是通过我的网站上的Codecademy学到了我的知识。我还使用提供的编辑器来运行代码。每次我都像这样运行它: puts "Enter a string!" user_input = gets.chomp user_input.downcase! us

我决定制作一个回文程序,但我是通过检查用户输入的字符串来实现的。为了做到这一点,我想去掉大写字母、空格和标点符号。除了标点符号部分外,我设法让所有的东西都工作了。每次我尝试使用“夫人,我是亚当”这样的字符串时,程序就会崩溃。我对Ruby很陌生,我只是通过我的网站上的Codecademy学到了我的知识。我还使用提供的编辑器来运行代码。每次我都像这样运行它:

puts "Enter a string!" 
user_input = gets.chomp
user_input.downcase!
user_input = user_input.gsub(/[^0-9a-z ]/i, '')
if user_input.include?(" ")
  user_input.gsub!(/ /, "")
end
if user_input == user_input.reverse
  print "Is a pallindrome"
else
  print "Is not a pallindrome"
end
puts "Enter a string!" 
user_input = gets.chomp
user_input.downcase!
if user_input.include?(" ")
  user_input.gsub!(/ /, "")
end
if user_input == user_input.reverse
  print "Is a pallindrome"
else
  print "Is not a pallindrome"
end
它崩溃了。但如果我像这样运行:

puts "Enter a string!" 
user_input = gets.chomp
user_input.downcase!
user_input = user_input.gsub(/[^0-9a-z ]/i, '')
if user_input.include?(" ")
  user_input.gsub!(/ /, "")
end
if user_input == user_input.reverse
  print "Is a pallindrome"
else
  print "Is not a pallindrome"
end
puts "Enter a string!" 
user_input = gets.chomp
user_input.downcase!
if user_input.include?(" ")
  user_input.gsub!(/ /, "")
end
if user_input == user_input.reverse
  print "Is a pallindrome"
else
  print "Is not a pallindrome"
end

它起作用了。我在这里做错了什么?为什么当我试图删除标点符号时,我的程序总是崩溃?

你的程序没有问题。Codecademy在读取任何包含引号的输入时出现错误

试一试:

gets
只需输入
即可看到它崩溃

我的建议是在ruby上开发自己的本地环境。有很多资源可以帮助您在任何操作系统上安装简单的ruby环境


之后,下载并安装升华文本,并开始创建ruby源文件。然后你会看到,
ruby.rb
会像你期望的那样完美地工作。

它会崩溃的原因是什么?…你输入了什么字符串,在哪一行发生了异常?下面是一些用ruby检查回文的其他方法:它告诉我程序“运行时间太长”,然后问我是否要停止它,或者试着让它继续下去。我试着使用字符串“夫人,我是亚当”,因为测试这个程序的人很可能会使用这个字符串。任何标点符号都会使它崩溃。