1

I'm kind of noob in ruby programming. My question is if there's something like anchors or goto in ruby, so I can create loops inside Ifs... Is there something like that?

Example:

anchorX
gets variable
if variable == "option one"
   puts "you choose right"
else
   puts "you choose wrong! DO IT AGAIN!"
go to anchorX
lurker
  • 56,987
  • 9
  • 69
  • 103

3 Answers3

3

No, Ruby does not have goto. Try a loop instead:

loop {
    input = gets.chomp
    if input == "option one"
        puts "you choose right"
        break
    else
        puts "you choose wrong! DO IT AGAIN!"
    end
}

Or, an alternative method (and arguably slightly more readable):

input = gets.chomp
until input == "option one"
   puts "you choose wrong! DO IT AGAIN!"
   input = gets.chomp
end
puts "you choose right"
tckmn
  • 57,719
  • 27
  • 114
  • 156
0

Why would you want to use goto for something so trivial?

Use a while loop. The while syntax for ruby is:

while [condition] do
   (put your code here)
end

For example:

gets variable
while variable != "option one" do
    puts "you choose wrong!"
    gets variable
puts "you choose right"
  • the Idea is not to repeat myself in a text only game... for example... the player can went back and redo the steps if he forgot something. A example would be: theres a table with a key and a door. If user writes go to door, there's a logic test varmovement =="pick key" he moves foward to the next if... elsif "open door" puts "the door is locked, do you need a key for that" and move the user back to the start of the conditional –  Aug 28 '14 at 01:27
0

Besides loop statements, you can use retry statement to repeat entire begin/end block.

begin
    input = gets.chomp
    if input == "option one"
        puts "you choose right"
    else
        puts "you choose wrong! DO IT AGAIN!"
        raise
    end
rescue 
    retry
end
Wenbing Li
  • 12,289
  • 1
  • 29
  • 41