0

I am looking for the proper way to do this in Ruby. I want to create an if/else statement that will keep looping until it finds the right answer. Example:

puts "Guess a number",prompt
$stdin.gets.chomp = x
if x == 5
   puts "correct
else
    # loop back to beginning and start over
end

2 Answers 2

4

You can use while statement to loop, if guess the number, then break, like this:

while true
  puts "Guess a number:"
  if gets.chomp.to_i == 5
     puts "correct"
     break
  end
  puts "guessed wrong, please try again!"
end

or use until statement:

puts "Guess a number:"
until gets.chomp.to_i == 5 do
  puts "guessed wrong, please try again!"
end

puts "correct"

as @izaban said, loop...do also can work:

loop do
  puts "Guess a number:"
  if gets.chomp.to_i == 5
     puts "correct"
     break
  end
  puts "guessed wrong, please try again!"
end
Sign up to request clarification or add additional context in comments.

1 Comment

You could also use loop do instead of while true
0

This is a solution without using break:

guess = 0
first_run_through = true

until guess == 5
  puts 'guessed wrong, please try again!' unless first_run_through
  first_run_through = false
  puts 'Guess a number'
  guess = gets.chomp.to_i
end

puts 'correct'

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.