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"
Related
puts "Hey what's your name?!!"
name = gets
puts "#outputNAME: #{name}"
puts "Hey #{name}! Howdy doin'!"
puts "Tell us 2 numbers that add up to your age!"
age1 = gets.to_i
age2 = gets.to_i
puts "Hey! You're #{age1 + age2} years old! Gotcha!"
puts "I'm totally new to Ruby on Rails, so thanks for running my first Ruby
Program. Please do leave an upvote and I'll appreciate that."
puts "If you think I need a downvote, please do state, in the comments
section, what I could have done to make my program better (my 1st program,
remember that #{name}). Also, check out my HTML pages, as I'm an ace at
HTML."
print "Thanks, once again #{name} and stay tuned (especially for my HTML
projects)!"
In this part, after #{name}, the sentence is continued on a new line, which I want not to happen. Is there any explanation as to what could be the error in my program, or is it an error in the language? Please help me, as I'm doing an individual project.
Thanks to whoever does find the solution to this problem.
it prints text to the new line after name, because you are accepting newline character in the following code.
name = gets
name = gets
raj
=> "raj\n"
you can remove such newline character by chomp method.
name = gets.chomp
raj
=> "raj"
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
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. :)
I understand about the \n that's automatically at the end of puts and gets, and how to deal with those, but is there a way to keep the display point (the 'cursor position', if you will) from moving to a new line after hitting enter for input with gets ?
e.g.
print 'Hello, my name is '
a = gets.chomp
print ', what's your name?'
would end up looking like
Hello, my name is Jeremiah, what's your name?
You can do this by using the (very poorly documented) getch:
require 'io/console'
require 'io/wait'
loop do
chars = STDIN.getch
chars << STDIN.getch while STDIN.ready? # Process multi-char paste
break if ["\r", "\n", "\r\n"].include?(chars)
STDOUT.print chars
end
References:
http://ruby-doc.org/stdlib-2.1.0/libdoc/io/console/rdoc/IO.html#method-i-getch
http://ruby-doc.org/stdlib-2.1.0/libdoc/io/wait/rdoc/IO.html#method-i-ready-3F
Related follow-up question:
enter & IOError: byte oriented read for character buffered IO
Perhaps I'm missing something, but 'gets.chomp' works just fine does it not? To do what you want, you have to escape the apostrophe or use double-quotes, and you need to include what the user enters in the string that gets printed:
print 'Hello, my name is '
a = gets.chomp
print "#{a}, what's your name?"
# => Hello, my name is Jeremiah, what's your name?
Works for me. (Edit: Works in TextMate, not Terminal)
Otherwise, you could just do something like this, but I realise it's not quite what you were asking for:
puts "Enter name"
a = gets.chomp
puts "Hello, my name is #{a}, what's your name?"
I am doing excercise 5.6 out of "Learn to Program" for a class. I have the following:
puts 'What\'s your first name?'
first = gets.chomp
puts 'What\'s your middle name?'
middle = gets.chomp
puts 'What\'s your last name?'
last = gets.chomp
puts 'Hello, Nice to meet you first middle last'
And I have tried the following:
puts 'What is your first name?'
first = gets.chomp
puts 'What is your middle name?'
middle = gets.chomp
puts 'What is your last name?'
last = gets.chomp
puts 'Hello, Nice to meet you #{first} #{middle} #{last}'
When I get the last "puts" it won't get the first, middle and last name that I wrote in. It says, "Hello, nice to meet you first, middle, last....Instead of Joe John Smith for example. What am I doing wrong?
Thank you so much for your help! I really appreciate it!
When using interpolation, use double quotes " instead of single quotes '
Strings within single quotes ' do not replace variables with their values. Try using double quotes " like so:
puts "Hello, Nice to meet you #{first} #{middle} #{last}"
Single qoutes are nice if you want the string as you typed it, double quotes are useful when you want to replace variable names with their values.
You can also use %Q to have the same effect as you get with double quotes ":
x = 12
puts %Q(I need #{x} pens)
# >> I need 12 pens