【问题标题】:How do you direct a user back to the beginning of a nested if statement?如何引导用户回到嵌套 if 语句的开头?
【发布时间】:2015-06-21 16:15:47
【问题描述】:

我正在尝试创建我的第一个应用程序,以帮助我理解 Ruby 的一些核心概念。这对你们大多数人来说非常简单且不言自明,我毫不怀疑。任何帮助是极大的赞赏。如果这看起来很愚蠢,我深表歉意,我刚刚开始并尽我所能解决这个问题。如果他们对“您要继续将水果添加到您的列表中吗?”回答“否”,我想添加查看列表的选项。我还希望应用程序在最后的最后一个 else 语句中让用户回到“然后告诉我你最喜欢的水果中的另一个!(输入“完成”以退出)”消息。我该怎么做呢?

# This app was created by: Daniel Horowitz

fruits = []

puts "Please tell me what one of your favorite fruits are... Do tell."
input = gets.chomp
fruits << input

puts "Yummy, that sounds delicious. You must tell me another!"
input = gets.chomp
fruits << input

puts "Do you want to keep adding fruits to your list?"
answer = gets.chomp.downcase

if answer == "yes"
  puts "Then tell me another of your favorites fruits! (Type 'done' to get out)"
  input = gets.chomp
  while input != "done"
    fruits << input
    puts "Would you like to see a list of you most favorite fruits?"
    input2 = gets.chomp.downcase
    if input2 == "yes"
      puts "These are your most dilectably delicious favorite fruits: #{fruits}"
    else

    end
  end
end

【问题讨论】:

    标签: ruby arrays if-statement while-loop


    【解决方案1】:
    fruits = []
    
    loop do # endless loop; see break
      puts "Type your fave fruit or “done” to exit:"
      input = gets.chomp
    
      break if input == 'done' # break a loop if “done” was entered
      fruits << input
    end
    
    puts "Would you like to see a list of you most favorite fruits?"
    if gets.chomp.downcase == "yes"
      puts "These are your most dilectably delicious favorite fruits: #{fruits}"
    end
    

    运行:

    # Type your fave fruit or “done” to exit:
    Apple
    # Type your fave fruit or “done” to exit:
    Orange
    # Type your fave fruit or “done” to exit:
    done
    # Would you like to see a list of you most favorite fruits?
    yes
    # These are your most dilectably delicious favorite fruits: ["Apple", "Orange"]
    

    希望对你有帮助。

    【讨论】:

    • 非常有用,感谢您花时间帮助我了解更多!
    猜你喜欢
    • 2014-12-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-02-22
    • 2012-06-01
    • 1970-01-01
    • 2016-04-23
    • 1970-01-01
    相关资源
    最近更新 更多