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
Related
I have the following methods that allow a user to ask for a drink up to 6 times. Each time they select a drink it may be a new, or the same drink from the menu list. How do I record the user response within each loop?
def display
menu_list = AlcoholicBeverage.pluck(:cocktail_name)
puts menu_list
sleep(0.1)
puts "So, what's your poison?" "\n"
end
def drink_valid?
chosen_cocktail = gets.chomp.titleize
until AlcoholicBeverage.find_by(cocktail_name: chosen_cocktail)
puts "Sorry please choose something on the list!"
chosen_cocktail = gets.chomp.titleize
end
puts "Mmmm good choice!"
puts "Now that you've chosen your cocktail, I'll provide you with details on the necessary ingredients,glass and garnishes!"
glass_type = AlcoholicBeverage.where(cocktail_name: chosen_cocktail).map(&:glass)
puts "Required : #{glass_type.join.titleize} glass."
garnish = AlcoholicBeverage.where(cocktail_name: chosen_cocktail).map(&:garnish)
if garnish.join.titleize == ""
puts "No garnish needed!"
else
puts "Required garnish: #{garnish.join.titleize}"
end
preparation = AlcoholicBeverage.where(cocktail_name: chosen_cocktail).pluck("preparation")
puts "To prepare : #{preparation.join}"
end
def ask
counter=0
while counter < 6
puts "Would you like another drink (yes/no)?"
new_drink = gets.chomp.strip.titleize
if new_drink == "Yes" || new_drink == "yes"
display
drink_valid?
else
puts "I'll give your blood alcohol content level based on the drinks you've had."
end
counter +=1
end
end
You can capture user input repeatedly by adding the user input to a variable from outside the loop:
# main.rb
inputs = []
until inputs.size >= 6
puts "Please input a value or leave blank to exit"
input = gets.chomp
break if input == ""
inputs << input
end
puts "You have input the following: #{inputs.inspect}"
$ ruby main.rb
Please input a value or leave blank to exit
1
Please input a value or leave blank to exit
2
Please input a value or leave blank to exit
3
Please input a value or leave blank to exit
4
Please input a value or leave blank to exit
5
Please input a value or leave blank to exit
6
You have input the following: ["1", "2", "3", "4", "5", "6"]
$ ruby main.rb
Please input a value or leave blank to exit
1
Please input a value or leave blank to exit
2
Please input a value or leave blank to exit
You have input the following: ["1", "2"]
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
puts 'guess my favorite num'
x = gets.chomp
unless x.kind_of?(Fixnum)
puts "it's not a Numeric symbol"
if x=="2"
puts "Well done!"
if x!=2 || x.is_a?(Fixnum)
puts "Try more, dude"
end
end
end
Trying to learn ruby, but my code is not work :-( Need 3 DIFFERENT conditions for var. Where is a bug ?
Consider this:
#!/usr/bin/env ruby
puts "Guess my favorite num."
x = gets.chomp
begin
if Integer(x) == 2
puts "Well done!"
else
puts "Try more, dude."
end
rescue ArgumentError
puts "It's not an integer."
end
Semi-contrived example, but you're probably looking for elsif:
puts 'enter a favorite num'
x = gets.chomp.to_i
if x == 2
puts "you entered 2"
elsif x !=2
puts "you did not enter 2"
end
Also--as #Jan Dvorak points out--the gets method returns a string, which you would want to convert (to integer in this case).
Another solution would be to use a case statement:
print 'enter a favorite num'
x = gets.chomp.to_i
case x
when 2
puts "you entered 2"
else
puts "you did not enter 2"
end
You did probably mean something like that:
loop do
puts 'guess my favorite num'
x = gets.chomp
case x
when /\D/
puts "it's not a Numeric symbol"
when "2"
puts "Well done!"
break
else
puts "Try more, dude"
end
end
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
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.