Reputation: 276
I can't get this program to respond properly to user input. Various looping techniques either only run the block once or run the block infinitely no matter what the user inputs (I've tried case
and while
as well). Here's the most recent method I've tried:
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 never objects to my syntax with any of the various methods, but it also never works.
Upvotes: 0
Views: 181
Reputation: 2670
I found two possibility over here which is suitable for you
First one is
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
Here Lopp will run until break Doesn't get executed
Second thing you can Modify 1 Line in your code which is
sprint = gets.chomp
this will extract last special character of your string which is generated by gets and work fine in your case
Upvotes: 2
Reputation: 6123
http://web.njit.edu/all_topics/Prog_Lang_Docs/html/ruby/syntax.html#begin
Begin is typically used for exception handling. I think you're looking for a while
loop.
Here is an example 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
Upvotes: 3
Reputation: 2142
You need
sprint = gets.chomp
gets returns string with trailing "\n".
Upvotes: 5