Is there a a "back to the top" in Ruby? [duplicate] - ruby

This question already has answers here:
Is there goto statement in Ruby?
(4 answers)
Closed 8 years ago.
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

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"

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"

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

Related

Accept multiple input possibilities for a single conditional branch

I have this code:
choice = $stdin.gets.chomp
if choice == "yes"
puts "ok sure"
else
puts "try again"
end
I have more than one possibility of user input to put "ok sure". That is, if I input "ok", it should still say "ok sure".
Use case construction.
case choice
when "yes", "ok"
puts "ok sure"
else
puts "try again"
end
Easiest way would be to use Array#include? like so:
choice = $stdin.gets.chomp
if ["yes", "ok"].include? choice
puts "ok sure"
else
puts "try again"
end

Prompt Menu in Ruby

I'm trying to create a simple prompt menu in Ruby. I'm not expert in Ruby but I'm trying to code something similar to the prompt menu in others languages like C/C++ but my code isn't working right, I'm geting a infinity loop on the user input and isn't calling the function.
Heres my code:
begin
puts "Option 1"
puts "Option 2"
puts "Option 3"
puts ""
command = gets.chomp
loop do
case command
when 1
functionname(arg1, arg2)
when 2
functionname2(arg1, arg2)
end
end
end
Please, someone can help me?
To ask for an option once, simply get rid of the loop (once ≠ loop):
puts ["Option 1", "Option 2", "Option 3", ""].join $/
case command = gets.chomp
when 1
functionname(arg1, arg2)
when 2
functionname2(arg1, arg2)
else
raise "Unknown option"
end
To request an option many times, ask inside loop:
loop do
puts ["Option 1", "Option 2", "Option 3", ""].join $/
case command = gets.chomp
when 1
functionname(arg1, arg2)
when 2
functionname2(arg1, arg2)
else
break # break loop
end
end

How to wrap a loop around an if statement [duplicate]

This question already has answers here:
Is there a "do ... while" loop in Ruby?
(10 answers)
Closed 8 years ago.
I'm coding a program that asks whether or not the user wants to give his name. If the user responds 'yes', the question is asked; on 'no' the program quits. If the users enter anything else, they are reminded to say either 'yes' or 'no'.
My code so far:
puts "Would you like to give us your name? (type yes or no)"
answer = gets.chomp
if answer == "yes"
print "What's your name?"
name = gets.chomp
puts "Nice to meet you, #{name}"
elsif answer == "no"
puts "Oh, ok. Good bye"
else
puts "You need to answer yes or no"
end
I need start over, if the user does not enter 'yes' or 'no' for the initial question.
You can solve that problem with a while loop, that breaks only when the correct input is made.
puts "Would you like to give us your name? (type yes or no)"
while answer = gets.chomp
case answer
when "yes"
print "What's your name?"
name = gets.chomp
puts "Nice to meet you, #{name}"
break
when "no"
puts "Oh, ok. Good bye"
break
else
puts "You need to answer yes or no"
end
end
answer = ""
while (answer != "yes" && answer != "no") do
puts "Would you like to give us your name? (type yes or no)"
answer = gets.chomp
end
if answer == "yes"
print "What's your name?"
name = gets.chomp
puts "Nice to meet you, #{name}"
elsif answer == "no"
puts "Oh, ok. Good bye"
else
puts "You need to answer yes or no"
end
This would be better accomplished creating a Method
Something like this will work for you:
def getname
# ask the user if we should continue
puts "Would you like to give us your name? (type yes or no)"
answer = gets.chomp
if answer == "yes"
# the user said yes. get the name
print "What's your name?"
name = gets.chomp
elsif answer == "no"
# the user said no. get out of here
puts "Oh, ok. Good bye"
else
# the user didnt answer correctly
puts "You need to answer yest or no"
# so we call this very function again
getname
end
end
# call the above method that we created
getname
What we did here was wrap your code in a method declaration. In that very method declaration we call that very method if the user doesnt supply the expected input.
Hope this helps.

Variables in if/else statement won't work

I'm creating an interactive story, not a game. The options don't work in the if/else; here is the code.
puts "Choose (1)yes or (2)no"
choice = gets.chomp
if #{choice}==1
puts "you chose yes"
elsif #{choice}==2
puts "you chose no"
else
puts "Invalid Choice"
I tried leaving it intro, but that just calls the else statement, and with this setup, the tic tac toe guy in front of the brackets, it always calls the first option. please help.
if #{choice}==1 isn't how you test the value of variables. #{} is for string interpolation; you don't have to interpolate anything. Just use if choice == "1". Note that, because you're reading a string from the console, you need to compare against "1", not 1.
puts "Choose (1)yes or (2)no"
choice = gets.chomp
if choice == "1"
puts "you chose yes"
elsif choice == "2"
puts "you chose no"
else
puts "Invalid Choice"
end

How do I loop a request for user input until the user enters the correct info?

I am a beginner who is trying to learn Ruby. I have learned some of the easier stuff so far, but I seem to be stuck in trying to combine a couple of things I've learned.
What I am trying to do is to ask the user a question and tell them to enter either 1 or 2. A simple if statement would let me respond with one option if they enter 1, and another option if they enter 2. However, if they enter something entirely different like a different number, a string, etc., how can I prompt them to try again and have it loop back to the original question?
What I have so far looks something like this.
prompt = "> "
puts "Question asking for 1 or 2."
print prompt
user_input = gets.chomp.to_i
if user_input == 1
puts "One response."
elsif user_input == 2
puts "Second response."
else
puts "Please enter a 1 or a 2."
end
This is where I'm stuck. How do I make it go back to the "Question asking for 1 or 2." until the user enters a 1 or 2? I know it's probably a loop of some kind, but I can't seem to figure out which kind to use and how to incorporate asking for user input repeatedly (if necessary) until getting the desired input. Any help would be greatly appreciated. Thanks.
You're right that you need to run your code in a loop. Using a while loop with gets.chomp as a condition, you can carry on asking for user input until you decide you've got what you want.
In this case, you want to validate the answer to the question and ask again if it's invalid. You don't need to change a great deal, except making sure you break out of the loop when the answer is correct. If the answer is wrong, print the prompt again.
This is a slightly refactored version that uses case instead, but it shows what you need to do. There is no doubt a cleaner way to do this...
prompt = "> "
puts "Question asking for 1 or 2."
print prompt
while user_input = gets.chomp # loop while getting user input
case user_input
when "1"
puts "First response"
break # make sure to break so you don't ask again
when "2"
puts "Second response"
break # and again
else
puts "Please select either 1 or 2"
print prompt # print the prompt, so the user knows to re-enter input
end
end
Try using the until method like this:
prompt = "> "
print prompt
user_input = nil
until (user_input == 1 or user_input == 2)
puts "Please enter a 1 or 2."
user_input = gets.chomp.to_i
end
if user_input == 1
puts "One response."
elsif user_input == 2
puts "Second response."
else
puts "Please enter a 1 or a 2."
end
user_input = 0
until [1,2].include? user_input do
puts "Please enter a 1 or a 2.>"
user_input = gets.chomp.to_i
end
if user_input == 1
puts "One response."
else
puts "Second response."
end
You can try this to make your code clean.
While the title of this question is somewhat unrelated, please see the trick that is used here: Ruby Retry and ensure block is not working
The use of error detection and unique retry keyword available in Ruby allows you to easily do a retry-loop compacted together with nice an error handling.
However, mind that the example I pointed is not really the best. There are some minor issues. For example, you should not catch Exception, rather simple rescue => e would be enough. But the overall idea should be rather clear.

Resources