Home > OS >  In Ruby, is there a way to have the user loop back through a conditional statement if they input the
In Ruby, is there a way to have the user loop back through a conditional statement if they input the

Time:05-11

I wonder if there is a way to use the if-else statements to trigger a loop that has the user re-enter a valid input? I have tried using the While loop as that type of structure technically works, but I cannot get the correct implementation. As of now, I have used an if-else conditional to individually test for each number in the valid range, and if the user inputs any of those values, it moves on. The else statement tells the user it is incorrect, but I can't seem to figure out a way to loop the user back until they enter a valid number. This is the code I am working with:

 class Humanoid < Player
  def play()
    userinput = print 'Enter your move [1 - 5]: '
    input = gets&.rstrip
    if input == '5'
      return input
    elsif input == '4'
      return input
    elsif input == '3'
      return input
    elsif input == '2'
      return input
    elsif input == '1'
      return input
    else
      return "That is not an option, choose again"
    end
  end
end

Is it possible to prompt the user to enter another number if it wasn't correct? I feel like it should be but I am currently stumped on what to do.

CodePudding user response:

I would use a simple loop that runs forever unless you explicitly return (or break) from it:

class Humanoid < Player
  def play()
    loop do
      print 'Enter your move [1 - 5]: '
      input = gets.chomp
    
      if %w[1 2 3 4 5].include?(input)
        return input
      else
        puts "That is not an option, choose again"
      end
    end
  end
end

Additionally, I cleaned up your conditions.

CodePudding user response:

I would write it like this:’

loop do
    userinput = print 'Enter your move [1 - 5]: '
    input = gets&.rstrip
    if input == '5'
      return input
    elsif input == '4'
      return input
    elsif input == '3'
      return input
    elsif input == '2'
      return input
    elsif input == '1'
      return input
    puts "That is not an option, choose again"
end 

Basically, this just makes it repeat forever until a value is returned. If none is, then the issue is printed and it loops again.

  • Related