Input with gets
Part of the Fundamentals section of Coddy's Ruby journey — lesson 29 of 88.
So far, you've learned how to display output. Now let's learn how to receive input from the user. The gets method reads a line of text that the user types in.
name = gets
puts "Hello, #{name}"When Ruby encounters gets, it waits for the user to type something and press Enter. Whatever they type gets stored in the variable. If the user types "Alice", the output would be:
Hello, Alice
There's something important to notice here. When the user presses Enter, that newline character gets included in the input.
That's why "Alice" appears with an extra blank line after it. The variable actually contains "Alice\n" where \n represents the newline.
You can use p to see this clearly:
name = gets
p nameIf the user types "Ruby", the output shows:
"Ruby\n"This trailing newline can cause unexpected behavior in your programs. In the next lesson, you'll learn how to remove it.
Challenge
EasyRead a name from the user using gets and store it in a variable called name.
Then use p to output the name variable, which will show the raw string including the trailing newline character.
For example, if the input is Ruby, your output should display the string with its quotation marks and the \n character visible.
Cheat sheet
The gets method reads user input from the console:
name = gets
puts "Hello, #{name}"When gets is executed, the program waits for the user to type something and press Enter. The input is stored in the variable.
The gets method includes the newline character (\n) when the user presses Enter:
name = gets
p name
# If user types "Ruby", outputs: "Ruby\n"Use p to display the raw string representation, which shows the newline character explicitly.
Try it yourself
# TODO: Read a name from the user using gets and store it in a variable called name
# TODO: Use p to output the name variableThis lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Fundamentals
4Operators Part 2
Logical Operators Part 1Logical Operators Part 2Recap - Simple LogicLogical Operators Part 3Logical Operators Part 42Variables and Data Types
Numbers and VariablesString Data TypeBoolean Data TypeSymbol Data TypeChecking Data TypesNaming ConventionsRecap - Variable Creation8Loops
For Loop with RangesWhile LoopBreakNextRecap - FactorialTimes LoopUntil LoopNested LoopsRecap - Dynamic Input3Operators Part 1
Arithmetic OperatorsModulo OperatorArithmetic ShortcutsRecap - Simple MathComparison Operators6Basic IO
Output with putsOutput with print and pOutput With VariablesInput with getsChomp MethodType ConversionRecap - Age CalculatorRecap - True or False