Jacob Wanner
Jacob Wanner

Reputation: 61

RUBY: If/Else statement that creates a loop

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

Upvotes: 0

Views: 1532

Answers (2)

ReggieB
ReggieB

Reputation: 8212

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'

Upvotes: 0

pangpang
pangpang

Reputation: 8821

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

Upvotes: 4

Related Questions