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
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.
Noob rubyist here, working through "Learn to Program." I've set up the below code to take user entries and sort, but I can't figure out how to end the program on a nil entry instead of the 'done' that is currently set. Setting the user == '', obviously terminates before it takes any input. Any help is greatly appreciated!
array = []
user = ''
puts "Type as many words as you like. Press enter to end."
until user == 'done'
user = gets.chomp
array.push user
end
puts
puts array.sort
Start your variable from nil, so that it executes the body at least the first time
user = nil
until user == ''
user = gets.chomp
array.push user
end
Here is another implementation that will not add the blank user to the array. Although it would be nice to use a construct more specific than loop, loop gives us exactly what we need.
users = []
loop do
user = gets.chomp
if user != ''
users << user
else
break
end
end
puts users
Your message says "Press enter to end". So I suggest you get the user input in one go, split the string into words, sort and display.
user = ''
puts "Type as many words as you like. Press enter to end."
user = gets.chomp
array = user.split
puts array.sort
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
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 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