Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

In Ruby, is there a way to have the user loop back through a conditional statement if they input the wrong range?

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading