为什么我的循环不起作用?

时间:2012-09-28 02:31:46

标签: ruby loops

我无法让这个程序正确响应用户输入。无论用户输入什么(我已尝试casewhile),各种循环技术要么只运行块一次,要么无限运行块。这是我尝试过的最新方法:

work_summary = []
begin
  # code that runs a sprint and adds results to the work_summary array
  puts "Would you like to add a sprint, Y/N?"
  sprint = gets.to_s
end until sprint == "N"
print work_summary, "\n"

Ruby永远不会使用任何各种方法反对我的语法,但它也永远无法工作。

3 个答案:

答案 0 :(得分:5)

你需要

sprint = gets.chomp

获取带尾随“\ n”的返回字符串。

答案 1 :(得分:3)

http://web.njit.edu/all_topics/Prog_Lang_Docs/html/ruby/syntax.html#begin

Begin通常用于异常处理。我想你正在寻找一个while循环。

这是一个例子 work_summary = []

while true
  puts "Would you like to add a sprint?"
  sprint = gets.chomp
  if sprint == "N"
    break
  elsif sprint == "Y"
    puts "What's your time?"
    time = gets.chomp
    work_summary << time
  else
    puts "I didn't understand your request. Enter Y or N"
  end
end

答案 2 :(得分:2)

我发现这里有两种适合你的可能性

第一个是

while true
  puts "Would you like to add a sprint?"
  sprint = gets.chomp
  if sprint == "N"
    break
  elsif sprint == "Y"
    puts "What's your time?"
    time = gets.chomp
    work_summary << time
  else
    puts "Wrong request. Enter Y or N"
  end
end

这里Lopp将一直运行直到休息不执行

第二件事你可以修改代码中的1行

sprint = gets.chomp

这将提取字符串的最后一个特殊字符,该字符由get生成并在您的情况下正常工作

相关问题