Reputation: 199
I wrote the following code:
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
I want to ask if the user wants to perform another operation:
puts "Would you like to perform another operation? Indicate 'Y' or 'N'"
another.operation = gets.chomp
If the user says N
, I would say something like puts "Thanks for your time! The app will be closed in one minute
. But if the user wants to run another operation (type Y
), I need to run all the code again. I know this can be done with while
, but don't know exactly. Any ideas?
Upvotes: 1
Views: 89
Reputation: 19855
You can maintain an infinite loop, and break
it when desired:
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
Upvotes: 4
Reputation: 59601
Use a boolean variable to switch between true
/false
based on user input. The first run it will be implicitly 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
Upvotes: 1