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"]
Related
I have a program that displays a numbered list and asks the user to input either a number or name from the list, and loops a block until the user enters "exit", after which it ends.
I want to add a line or two that puts an error message like, "Sorry, I don't seem to understand your request" if the user inputs something that is not on the list (name/number) and is not the word "exit".
I can't seem to figure it out. Any advice? My current code is below.
def start
display_books
input = nil
while input != "exit"
puts ""
puts "What book would you more information on, by name or number?"
puts ""
puts "Enter list to see the books again."
puts "Enter exit to end the program."
puts ""
input = gets.strip
if input == "list"
display_books
elsif input.to_i == 0
if book = Book.find_by_name(input)
book_info(book)
end
elsif input.to_i > 0
if book = Book.find(input.to_i)
book_info(book)
end
end
end
puts "Goodbye!!!"
end
Seems that you should add an elsif statement in this if:
if book = Book.find_by_name(input)
book_info(book)
elsif input != 'exit'
puts "Sorry, I don't seem to understand your request"
end
A good template for an interpreter is to build around Ruby's very capable case statement:
loop do
case (gets.chomp.downcase)
when 'list'
display_books
when /\Afind\s+(\d+)/
if book = Book.find($1.to_i)
book_info(book)
end
when /\Afind\s+(.*)/
if book = Book.find_by_name($1)
book_info(book)
end
when 'exit'
break
else
puts "Not sure what you're saying."
end
end
Although this involves regular expressions, which can be a bit scary, it does give you a lot of flexibility. \A represents "beginning of string" as an anchor, and \s+ means "one or more spaces". This means you can type in find 99 and it will still work.
You can create a whole command-line interface with it if you take the time to specify the commands clearly. Things like show book 17 and delete book 17 are all possible with a bit of tinkering.
I have a task to puts an infinite number of word, each in one line to array, and when enter is pressed on an empty line, puts these words in reverse order. How can I define when enter is pressed or empty line is input?
Code is here:
word = []
puts "Enter word"
add = 0
until add == ????
word.push gets.chomp
add = word.last
end
puts word.reverse
Here's a possible solution, with comments. I didn't see any useful role being played by your add variable, so I ignored it. I also believe in prompting the user regularly so they know the program is still engaged with them, so I moved the user-prompt inside the loop.
word = [] # Start with an empty array
# Use loop when the terminating condition isn't known at the beginning
# or end of the repetition, but rather it's determined in the middle
loop do
print 'Enter word: ' # I like to prompt the user each time.
response = gets.chomp # Read the response and clean it up.
break if response.empty? # No response? Time to bail out of the loop!
word << response # Still in the loop? Append the response to the array.
end
puts word.reverse # Now that we're out of the loop, reverse and print
You may or may not prefer to use strip rather than chomp. Strip would halt if the user input a line of whitespace.
Here, this is a modified version of your code and it works as requested.
word = []
puts "Enter word"
add = 0
while add != -1
ans = gets.chomp
word.push ans
if ans == ""
puts word.reverse
exit
end
add += 1
end
puts word.reverse
This is another version, using (as you did originally) the until loop.
word = []
puts "Enter word"
add = 0
until add == Float::INFINITY
ans = gets.chomp
word.push ans
if ans == ""
puts word.reverse
exit
end
add += 1
end
puts word.reverse
This is a follow up to one of my previous questions. When I run this program, the arrays are shown as ["1", "2", "3] etc.
This is my code:
#Table of Contents using an array
linewidth = 50
title = "Table of Consents"
#Needs chapters inputted
chapters = Array.new
puts "Please input chapter names."
while (input = gets.chomp) != ""
break if input.chomp.empty?
chapters << input
end
#Needs corresponding page numbers inputted
pagenumbers = Array.new
puts "Please input corresponding page numbers."
while (pagenum = gets.chomp) != ""
break if pagenum.chomp.empty?
pagenumbers << pagenum
end
leftside = chapters.to_s
rightside = "Pg. " + pagenumbers.to_s
puts title.center(50)
puts leftside.ljust(30) + rightside.rjust(30)
When I run it, it looks like this.
MBP-ERDOS:Programs chriserdos$ ruby TOCarray.rb
Please input chapter names.
born
dead
live
Please input corresponding page numbers.
1
43
99
Table of Consents
["born ", "dead", "live"] Pg. ["1", "43", "99"]
I'd like for the array to be printed like this:
born
dead
live
with the corresponding page numbers right justified on the same line.
New to Ruby, thank you for your help!
Get rid of all the code after your while loop and put this instead:
data = chapter.zip(pagenumbers)
puts title.center(50)
data.each do |left, right|
puts left.ljust(30) + right.rjust(30)
end
Just the strict answer to your question is:
puts title.center(50)
leftside.each_with_index { |x, i| puts "#{x.ljust(30)}#{rightside[i].rjust(30)}" }
But there is more methods to do it. Please take time to do some Ruby course or read a book, it is worth to do it.
I'm having a problem with my ruby script. If anyone could help, I'd really appreciate it. The problem is that the number is stuck between 1-2; where 2 is too high and 1 is too low. The guesses should be integers only.
#!/usr/bin/ruby
def highLow(max)
again = "yes"
while again == "yes"
puts "Welcome to the High Low game"
playGame(max)
print "Would you like to play again? (yes/no): "
again = STDIN.gets.chomp
if again == 'no'
puts "Have a nice day, Goodbye"
end
end
end
#This method contains the logic for a single game and call the feedback method.
def playGame(max)
puts "The game gets played now"
puts "I am thinking of a number between 1 and #{max}." #It show what chosen by user
randomNumber = rand(max)+ 1
print "Make your guess: "
guess = STDIN.gets.chomp
feedback(guess, randomNumber)
end
#Start while loop
#Logic for feedback method. It's ganna check the guess if it's high or low.
def feedback(guess, randomNumber)
count = 1
while guess.to_i != randomNumber
count = count + 1
if guess.to_i < randomNumber
print "That's too low. Guess again: "
else
print "That's too high. Guess again: "
end
guess = STDIN.gets.chomp
end
puts "Correct! You guessed the answer in #{count} tries!"
end
highLow(ARGV[0])
Change your last line to this:
highLow(ARGV[0].to_i)
The ARGV array contains all the passed in arguments as strings, so you have to cast it to integer.
I'm making a software but I don't want to publish it's source code right now because I don't want people to steal my hard work. I'm not rude or anything like that. Below is an example of what the program I'm making looks like.
print "Username : "
name = gets.chomp
print "Password : "
pass = gets.chomp
if name =="user" and pass=="pa$$word"
print "Hello"
else print "Error, incorrect details"
Now this is a simplest login form in ruby but what bad happens here is whenever the user inserts wrong information the program will simply shutdown and what I want to happen is that I want to keep the program asking the user for right information until right information is inserted.
Are you a windows user? Do know how to program in batch files?
examples
echo Hello world
cls
pause
So here is the code for ruby
a. print "Command : "
b. command = gets.chomp
c. if command == "Hello"
d. print "Hi, how are you?"
e. elsif command == "help"
f. print "Say hi to me, chat with me"
now what I want here too is just like in the first question
Details : After the user types in "Hi" the program just shuts down but what I want here it to make the program ask go to line a again
Use a while loop which continually asks for entry and checks the user's submission until a valid result is entered.
username = nil
while username.nil?
puts "What is your username?"
entered_username = gets.chomp
if entered_username == "Bob"
username = entered_username
end
end
puts "Thanks!"
When run on the terminal this produces:
What is your username?
sdf
What is your username?
dsfsd
What is your username?
sdfsd
What is your username?
sdfds
What is your username?
sdf
What is your username?
Bob
Thanks!
1.
until (print "Username : "; gets.chomp == "user") and
(print "Password : "; gets.chomp == "pa$$word")
puts "Error, incorrect details"
end
puts "Hello"
2.
loop do
print "Command : "
case gets.chomp
when "Hello" then print "Hi, how are you?"; break
when "help" then print "Say hi to me, chat with me"; break
end
end
Here is the easy method :) If anyone is stuck with the problem I encountered all you do is this. The "while" loop
number = 1 # Value we will give for a string named "number"
while number < 10 # The program will create a loop until the value
# of the string named "number" will be greater than 10
puts "hello"
# So what we need to do now is to end the loop otherwise
# it will continue on forever
# So how do we do it?
# We will make the ruby run a script that will increase
# the string named "number"'s value every time we run the loop
number = number + 1
end # Now what happens is every time we run the code all the program
# will do is print "hello" and add number 1 to the string "number".
# It will continue to print out "hello" until the string is
# greater than 10