Getting User Input
Prerequisites: Strings
gets ("get string") pauses the program, waits for the user to type a
line and press Enter, and returns what they typed.
Syntax
name = gets.chomp
gets includes the Enter key as a newline character ("\n") at the
end. chomp removes it. You'll almost always write the two together.
Example
print "What's your name? "
name = gets.chomp
puts "Nice to meet you, #{name}!"
Expected output
What's your name? Ada
Nice to meet you, Ada!
(Ada is what the user typed.) Using print for the question keeps
the cursor on the same line as the prompt.
Input is always text
gets always returns a string, even if the user types a number.
Convert it before doing maths — the next lesson covers how:
print "How old are you? "
age = gets.chomp.to_i
puts "In ten years you'll be #{age + 10}."
Common mistakes
- Forgetting
chomp:"Ada\n"then printsNice to meet you, Adawith the!pushed onto a new line. - Doing
gets.chomp + 10— aTypeError, because the input is text. - When a script's input is piped in and runs out,
getsreturnsnil, andnil.chompraisesNoMethodError.gets.to_s.chompavoids it.
Practice
Ask the user for their favorite color and print it back in capitals,
like BLUE is a great color!.
Show solution
print "Favorite color? "
color = gets.chomp
puts "#{color.upcase} is a great color!"