Question

I have the loop below and its behavior seems strange to me.

It's part of a BlackJack game and it is asking for the user to input a bet. If the bet is more than the amount of money the user has then it loops back around.

c is equal to 500 here:

b = 90000000
until b < c
  puts "You have $" + c.to_s + "."
  puts "How much do you want to bet? "
  b = gets.to_i
  if b < c
    @bet = gets.to_i
  else
    puts "Nice try."
  end
end

I set b to a high number to ensure that the loop is run at least once. When I start the loop and enter numbers higher than the money I have, it does what it's supposed to, and loops asking for a bet. But, when I finally enter a valid amount the loop gets stuck.

Then when I set b to a low enough number so that it skips over the until everything works fine.

Does anyone know why my loop is sticking?

Was it helpful?

Solution

It's not 'sticking', it's waiting for IO.

You have a second call to gets inside your if b < c block. Your loop is executing the final time, you are entering a value < c, your if block is entered, and your program is waiting for you to read more input.

Change your inner if block to

if b < c
  @bet = b
else
  puts "Nice try."
end

and you should be ok.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top