如果用户想要执行另一个操作,则使用`while`重复该过程

时间:2015-12-31 20:48:12

标签: ruby while-loop

我写了以下代码:

puts "Money to deposit:"
money_invested = gets.to_f

puts "Time in days:"
time_investment = gets.to_f

puts "Indicate interest rate:"
interest_rate = gets.to_f

investment_calculation =
money_invested * (1 + interest_rate / 100 * time_investment / 365)
puts "Your money will be: $%.2f." % investment_calculation

我想询问用户是否想要执行其他操作:

puts "Would you like to perform another operation? Indicate 'Y' or 'N'"
another.operation = gets.chomp

如果用户说N,我会说puts "Thanks for your time! The app will be closed in one minute之类的内容。但是如果用户想要运行另一个操作(类型Y),我需要再次运行所有代码。我知道这可以通过while完成,但并不完全清楚。有什么想法吗?

2 个答案:

答案 0 :(得分:4)

您可以保持无限循环,并在需要时break

NO = %w{ n no nope negative negatory nyet }
loop do
  # all of your various questions & responses

  puts "Would you like to perform another operation? Indicate 'Y' or 'N'"
  response = gets.chomp
  break if NO.include?(response.downcase)

  # Additional code could go here, if it's appropriate
  # to perform repeated actions after user indicates
  # they don't want to quit
end

# cleanup code here

答案 1 :(得分:1)

使用布尔变量根据用户输入在true / false之间切换。第一次运行将隐式true

do_loop = true
while do_loop

    puts "Money to deposit:"
    money_invested = gets.to_f

    puts "Time in days:"
    time_investment = gets.to_f

    puts "Indicate interest rate:"
    interest_rate = gets.to_f

    investment_calculation = money_invested * (1 + interest_rate/100 *     time_investment/365)
    puts "Your money will be: $%.2f." % investment_calculation

    puts "Would you like to perform another operation? Indicate 'Y' or 'N'"
    answer = gets.chomp

    # assign "true" to loop variable only if first character is 'Y' or 'y'
    do_loop = answer.size > 0 && answer.downcase[0] == 'y'
end