`gets`not working when used in `if...end`statement - ruby

I want to find a way for my script to wait until the user hits ENTER, while using a if...end
input = 3
if input > 2
puts "input is greater than 2"
gets
puts "this shouldn't appear before I type ENTER"
end
This does not work as I get
$input is greater than 2
$this shouldn't appear before I type ENTER
what should I use instead of gets to pause the script ?
Thank you for your time

Try to replace gets with $stdin.gets

Its working for me, are your sure you want to read from console?
input = 3
if input > 2
puts "input is greater than 2"
puts "please enter your name"
name = gets
puts "hi #{name} this shouldn't appear before I type ENTER"
end
o/p
~/Desktop$ ruby demo.rb
input is greater than 2
please enter your name
salil
hi salil
this shouldn't appear before I type ENTER

Related

how can I store each instance of the loop?

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"]

How to create a user defined exception in Ruby from user input

I am trying to create a user defined error where, if the user enters their first name only, it raises an error and tells the user to try again or, if they enter a numeral, it will raise an error.
This is my code but when I run it it outputs "Enter your first and last name" then it rescues it no matter if I enter a full name. It still says "Sorry I didn't quite catch that." then concatenates it:
class MyNewException < Exception
attr_reader :first, :last
def initialize(first)
#first = first
end
end
print "Enter your first and last name: "
begin
first = gets.chomp
last = gets.chomp
#prompt the user to enter first and last name
rescue MyNewException
puts "Sorry I didn't quite catch that. Try again."
gets
else
puts "Hello, " + first + last + "!"
end
gets will grab everything you type before pressing Enter. So first actually includes the first and last name that you are entering, and then last is empty. It looks like they are being concatenated, but all the text is in first. If you enter your first name, then press Enter, then enter your second name, then it should output both names.
The error is not being raised. You need to add something like this if you want to raise the error when last is blank:
last = gets.chomp
if last == ""
raise MyNewException, first
end

Dynamic constant assignment Ruby [duplicate]

This question already has answers here:
Dynamic constant assignment
(7 answers)
Closed 2 years ago.
I have been following a tutorial to create a typing challenge. I have taken care to follow this carefully. When i try to run the script from the command line i keep getting the following error and i do not understand it. I think the tutorial might be quite old but if someone could give me some guidance to understand it so i can fix it then that would be so appreciated! The error i get when i run the script from the command line is as follows....
Typechallenge.rb:89: dynamic constant assignment
Console_Screen = Screen.new
^
typechallenge.rb:90: dynamic constant assignment
Typing_Test = Test.new
The script itself is below...
#Script name: Typing Challenge
#Description: Demonstrating how to apply conditional logic in order to analyze user input and control
#the execution of the script through a computer typing test.
class Screen
def cls
puts ("\n" * 25)
puts "\a"
end
def pause
STDIN.gets
end
end
class Test
def display_greeting
Console_Screen.cls
print "\t\t Welcome to the Typing Challenge" +
"\n\n\n\n\n\n\n\n\n\n\n\n\nPress Enter to " +
"continue. \n\n: "
Console_Screen.pause
end
def display_instructions
Console_Screen.cls
puts "\t\t\tInstructions:\n\n"
puts %Q{ This test consists of five typing challenges. Each sentence is a challenge and are presented one at a time. To respond
correctly you should retype each sentence exactly as it is shown and the press the Enter key. Your grade will be displayed at
the end of the test.\n\n\n\n\n\n\n\n\n
Press Enter to continue.\n\n}
Console_Screen.pause
End
def present_test(challenge)
Console_Screen.cls
print challenge + "\n\n: "
result = STDIN.gets
result.chop!
if challenge == result then
$noRight += 1
Console_Screen.cls
print "Correct!\n\nPress Enter to continue."
Console_Screen.pause
else
Console_Screen.cls
print "Incorrect!\n\nPress Enter to continue."
Console_Screen.pause
end
end
def determine_grade
Console_Screen.cls
if $noRight >= 3 then
print "You retyped " + $noRight.to_s + " sentence(s) correctly. "
puts "You have passed the typing test!\n\nPress Enter to continue."
else
print "You retyped " + $noRight.to_s + " sentence(s) correctly. "
puts "You have failed the typing test!\n\nPress Enter to continue."
end
end
#Main script logic
$noRight = 0
Console_Screen = Screen.new
Typing_Test = Test.new
Typing_Test.display_greeting
Console_Screen.cls
print "Would you like to test your typing skills? (y/n)\n\n: "
answer = STDIN.gets
answer.chop!
until answer == "y" || answer == "n"
Console_Screen.cls
print "Would you like to test your typing skills? (y/n)\n\n: "
answer = STDIN.gets
answer.chop!
end
#Analyzing the players response
if answer == "n"
Console_Screen.cls
puts "Okay, perhaps another time! \n\n"
else
Typing_Test.display_instructions
Typing_Test.present_test "In the end there can be only one"
Typing_Test.present_test "Once upon a time a great plague swept across the land"
Typing_Test.present_test "Welcome to the typing challenge"
Typing_Test.present_test "There are very few problems in the world" + "that enough M&Ms cannot fix."
Typing_Test.present_test "Lets play this game of life together"
Typing_Test.determine_grade
Console_Screen.pause
Console_Screen.cls
puts "Thank you for playing the game!\n\n"
end
end
end
Names that start with upper-case letter are constants. In your code you assign a non-constant (dynamic) value to a name that represents a constant. Hence the error.
Console_Screen = Screen.new
Use local variable name convention (snake_case)
console_screen = Screen.new

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.

I need help in ruby

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

Resources