I want to check if a field was filled in. I have an imcompleted code:
print "What is your name?"
user_input = gets.chomp.upcase
if user_input = ??
print "Nice to meet you user_input!"
else
puts "Please enter your name."
end
How do I complete the code to do that?
Under the premise that you would like to:
Print out a message: "What is your name?"
Have the user enter their name and store it in the user_input variable(with gets.chomp)
Output either "Nice to meet you << user name >>" or "Please enter your name" depending on whether the input matches certain criteria
...we have a few changes to make.
The first being the condition of checking to make sure the input isn't blank and the second being seeing if the input matches a certain value.
First, let's check to see if the input is empty before continuing. We can use String#empty to make sure the string has at least one character (including whitespace):
print "What is your name?"
user_input = gets.chomp.upcase
# Check to make sure the input isn't empty
if !user_input.empty?
print "Nice to meet you user_input!"
else
puts "Please enter your name."
end
Then, we can check to see if the input matches certain criteria. Unfortunately, your question doesn't specify what these criteria are, so as other users are suggesting you can use regex to see if it matches a particular pattern, or just use a hard coded string to compare:
print "What is your name?"
user_input = gets.chomp.upcase
# After making sure the input is empty, check to make sure it matches the string "Bob"
if !user_input.empty? && user.input == "Bob"
print "Nice to meet you user_input!"
else
puts "Please enter your name."
end
Lastly, there is one bug in the code. The output once a user's input has been validated will always be "Nice to meet you user_input", even when the user_input variable is another value. This is because we aren't using String Interpolation properly:
print "What is your name?"
user_input = gets.chomp.upcase
if !user_input.empty? && user.input == "Bob"
# When using string interpolation, surround the variable you'd like to print with #{}
print "Nice to meet you #{user_input}!"
else
puts "Please enter your name."
end
As other users have stated, you should consider fine tuning the requirements of your problem a bit more. You can add a lot of detail and experimentation to this simple example!
There's a lot of context missing from the question, but there are a couple of things that may be helpful to you.
Basic check if it's nil or empty:
if user_input.nil? || user_input.empty?
# Ask the user to try again
end
Check if it matches a pattern you specify using a Regex (see https://ruby-doc.org/core-2.1.1/Regexp.html). For example:
if user_input =~ /^[[:upper:]][[:lower:]]+/
# One uppercase character, followed by at least one lowercase
end
The second option has far more possibilities, but again it depends on your needs.
if user_input.blank?
puts "please enter your name"
else
puts "Nice to met you"
end
Related
I want in brief to run a program to check if the user input is empty to let him reinsert the needed data and in case there is "s" in the string to be substituted with another letter
print "Please enter a string: "
user_input = gets.chomp.downcase!
if user_input.empty?
print "Please enter a vaild string... "
user_input = gets.chomp.downcase!
elsif
user_input.include? "s"
user_input.gsub!(/s/, "th")
else
puts "There are no 's's in your string. #{user_input}"
end
puts "Your new thtring is #{user_input}."
The problem is with this line
user_input = gets.chomp.downcase!
according to the docs
Downcases the contents of str, returning nil if no changes were made.
So if the user inputs a string with only lowercase letters, nil is returned.
Your function works if a user enters FOO, then it works fine.
You're better off using downcase instead of downcase!. downcase always return the string itself.
As I understand you need get valid user input (with s)
Now you are only using if and this does not guarantee that user input will be valid
You can refactor to something like this
puts "Please enter a string with s:"
thtring = ""
loop do
user_input = gets.chomp
next puts "Please enter some string..." if user_input.empty?
thtring = user_input.downcase
next puts "There are no 's's in your string" unless thtring.include?("s")
break thtring.gsub!(/s/, "th")
end
puts "Your new thtring is #{thtring}."
I'm trying to loop this question until the user's input is a string value:
Question: What is your name?
I don't want the user to just press enter and leave the name blank.
I don't want the user's input to be numeric/numbers.
Please see my code below:
name1 = gets.chomp.to_s
loop do
print "Please enter your name "
name1 = gets.chomp.to_s
if name1.empty?
puts "No input."
else name1.to_i
puts "Illegal character ':'"
end
end
With this code, I can't proceed to the next question even if I input a string value. Please help.
Your code has several issues:
Your input and output is out of order. You gather input before prompting and that input (from your first line) is never used:
name1 = gets.chomp.to_s # <- Ruby is waiting for input
loop do
print "Please enter your name " # <- user is prompted to enter name
name1 = gets.chomp.to_s # <- previous input is overwritten
# ...
end
The first line should probably be deleted.
gets might return nil, but chomp always returns a string. Calling to_s afterwards is therefore superfluous.
Your if-else construct is actually:
if name1.empty?
puts "No input."
else
name1.to_i
puts "Illegal character ':'"
end
So whenever the input is not empty?, you convert it to an integer (discarding the result) and print an error message. You probably want an elsif instead (/.../ is a regexp and \d matches a digit):
if name1.empty?
puts 'No input.'
elsif name1.match? /\d/
puts 'Digits not allowed.'
end
You could also use a case expression:
case name1
when ''
puts 'No input.'
when /\d/
puts 'Digits not allowed.'
end
You never break out of your loop. The code keeps looping even if no error was found. This can be fixed by adding a break statement in an else branch (to either if or case):
# ...
else
break
end
gets.chomp will always return a string, and as such there is no need to call to_s on the method.
If you don't want the user to be able to input any integers, you could use the following for a clean solution:
name.count("0-9") > 0
If this returns true, then you know that the user's input contains at least one number.
Just started Ruby yesterday (for the first time). And struggling a bit. Please help.
Here's the program:
print "What's your name?"
name = gets.chomp
if name == "James"
print "Someone loves you!"
else
print "Try again #{name}!"
end
print "How old are you?"
age = gets.chomp
if age <= "25"
print "Boy, you are just a child"
elsif age >= "45"
print "Shame on you old man, craddle snacher!"
end
The output is:
enter image description here
So my concern is; why is it not beginning from a new line after "Try again Jack". I would like all the questions and answers to start at a fresh line. Please help!
PS: Just ignore the content of the program. That was just something to keep myself motivated. I don't really mean to be offensive.
2 options, print with explicit linebreaks ( \n , also works on Windows), or puts which adds a linebreak if the string does not already ends with one. These two examples result in the same output:
print "Hello\nworld\n"
puts "Hello
world"
I am creating a Daffy Duck speech converter (Very simple. Straight from CodeCademy) and I am having an issue with displaying the modified entry from the user.
Code:
puts "What would you like to convert to Daffy Duck language?"
user_input = gets.chomp
user_input.downcase!
if user_input.include? "s"
user_input.gsub!(/s/, "th")
print #{user_input}
else puts "I couldn't find any 's' in your entry. Please try again."
end
It will change any 's' in your entry to a 'th', therefore, making it sound like a Daffy Duck once read aloud. When I enter it into the interpreter, it will not display the modified string. It will just display the original entry by the user.
EDIT:
Thanks to the users below, the code is fixed, and I added a notice to the user with converted text. Thanks guys!
A # outside a string starts a comment, so #{user_input} is ignored, i.e.
print #{user_input}
is equivalent to
print
You might wonder why a single print outputs the original input. This is because without arguments print will print $_. That's a global variable which is set by gets:
user_input = gets.chomp # assume we enter "foo"
user_input #=> "foo"
$_ #=> "foo\n"
Everything works as expected if you pass a string literal:
print "#{user_input}"
or simply
print user_input
Note that gsub! returns nil if no substitutions were performed, so you can actually use it in your if statement:
if user_input.gsub!(/s/, "th")
print user_input
else
puts "I couldn't find any 's' in your entry. Please try again."
end
You just need to add double quotes around the string interpolation. Otherwise your code was just returning the input.
puts "What would you like to convert to Daffy Duck language?"
user_input = gets.chomp
user_input.downcase!
if user_input.include? "s"
user_input.gsub!(/s/, "th")
print "#{user_input}"
else
puts "I couldn't find any 's' in your entry. Please try again."
end
You don't even need interpolation, actually. print user_input works. Notice how StackOverflow was even syntax highlighting your code as a comment. :)
how do I loop if a condition is not met?
print "Please enter first number "
first_number = gets.chomp
if first_number =~ /[a-zA-Z]/
puts "not a number"
end
As per the code posted above, if you enter a letter, you'll get the statement of it not being a number.
How do I repeat it, if a user enters a letter?
As of now, it goes to the next one which is this:
print "Please enter second number "
second_number = gets.chomp
if second_number =~ /[a-zA-Z]/
puts "not a number"
end
I don't want it to it to go to the next one, until the user has entered a number in the first one.
You can use while and until as a modifier to a block. This will run the block first and then check a conditional and run the block again until it passes, which is the behavior you want.
begin
puts 'Please enter first number'
first_number = gets.chomp
end until first_number =~ /\d+/
I suggest you consider doing it like this:
num = nil # initialize to anything
loop do
puts 'Enter a number'
num = gets.chomp.strip
case num
when /^\d+$/
break
when /^[a-z]+$/i
print "You entered one or more letters and no digits."
else
print "You made some other illegal entry."
end
puts " Try again"
end
puts "You enterered the number #{num}"
Some notes:
num must be initialized (to anything) before the loop in order for it to be visible after the loop's end statement.
the case statement, since it uses === for evaluating when expressions, allows you to enter a regex for each case.
^ and $ in the regexes are anchors, so that, for example, "34b" =~ /^\d+$/ => nil (what I assume you want), rather than "34b" =~ /\d+/ => 0.
the i in /[a-z]+$/i allows matching letters to be uppercase or lowercase.
the user may enter one or more digits, or one or more letters, but there are many other possibilities as well ("3$,a"), so I added another "catch-all" possibility in the case statement.