Thuta Learning
Ruby
BasicProgrammingBeginner

User Input (gets)

RubyLesson 830 min

What you'll walk away with

  • Read a line with gets and clean it with chomp and strip
  • Explain why gets returns nil at the end of input and how that makes gets.chomp raise NoMethodError
  • Convert text to numbers with to_i, Integer() and Integer(text, exception: false) and know how they differ
  • Test input code without a keyboard by replacing $stdin with a StringIO

Explain it simply

Explain it simply

When a program calls gets, it stops and waits, like a clerk asking you to fill in a form field. You type some text, press Enter, and the program carries on with whatever you typed. That text comes back as a String, always, even when you typed digits.

Because Enter is part of what you typed, the string ends with a newline character, and that is why almost every gets in real code is followed by chomp. Think of chomp as trimming the line break off the end of the answer so that "Aung" is just "Aung".

Problem → Why → Solution

The problem: it works in your terminal and breaks everywhere else

A first input program often works perfectly in your terminal and then fails in two different ways. If you store age = gets.chomp and later compute age + 1, Ruby raises a TypeError, because "20" is text and you cannot add a number to text. And if somebody runs the same script with nothing to read, for example with ruby age.rb < /dev/null or inside an automated test, it crashes before it even prints a greeting.

Both failures have the same root: gets gives you raw, possibly missing text, and your code treated it as a clean number.

age.rb
print "How old are you? "
age = gets.chomp                 # NoMethodError if there is no input at all
puts "Next year: #{age + 1}"     # TypeError: String + Integer

Why is text from gets unreliable?

Input crosses the boundary between your program and the outside world, and nothing out there promises it is complete or well formed. gets can return nil when the input has ended, and even a real answer is just characters until you convert it. Treat every line you read as untrusted text: remove the newline, convert it on purpose, and decide what to do when it is missing or invalid.

Core concept: gets returns a line or nil

gets reads one line from standard input and returns it as a String that still ends with the newline character, or returns nil when the input has run out. The input can be a person typing at a terminal, a file redirected with <, or the output of another program piped in. In a terminal you can end the input yourself with Ctrl-D (Ctrl-Z followed by Enter on Windows), which makes the next gets return nil.

chomp removes one trailing newline (also the Windows pair \r\n) and nothing else, so "Aung\n".chomp is "Aung" but " Aung \n".chomp keeps its spaces. strip removes whitespace from both ends, which is handy for answers like " yes ". Without it, a comparison such as answer == "yes" is false because the string is really "yes\n".

Everything that arrives is a String. To get a number you must convert it, and the three ways behave very differently: to_i never complains, Integer() raises ArgumentError for text that is not a whole number, and Integer(text, exception: false) returns nil instead, so you can test the result with a plain if. Integer() also reads a leading 0 as octal, so "09" is rejected, while passing the base, as in Integer(text, 10), forces ordinary decimal.

Because gets can return nil, gets.chomp is only safe when you know input exists. gets&.chomp keeps nil as nil, and gets.to_s.chomp turns nil into an empty string. One more detail: Kernel#gets reads the files named on the command line first and only reads standard input when there are none, so use $stdin.gets when you must always read what a user types.

Finally, standard input is just an object stored in $stdin. Replace it with StringIO.new("Aung\n20\n") and the same gets calls read from that string, which lets you run and test input code in scripts, automated tests and the lesson examples without waiting for a keyboard.

Mental model: gets returns a line or nil
  1. The program waits at gets
  2. You type and press Enter
  3. gets returns a String, or nil at EOF
  4. Clean and convert before using it

Input is always text and may be missing: clean it, convert it on purpose, and decide what happens when it is nil.

General pattern

ruby
require "stringio"                       # only needed to fake input

line = gets                              # String ending in "\n", or nil at end of input
text = line&.chomp                       # nil-safe: stays nil when nothing was read
number = Integer(text, 10, exception: false)   # nil when text is not a whole number

$stdin = StringIO.new("typed text\n")    # test double: gets now reads this string

gets gives a line or nil, &.chomp passes nil through without crashing, and Integer(text, 10, exception: false) gives nil for text that is not a whole number. The last line replaces $stdin with a StringIO so gets reads from that string instead.

Example: a program that asks for a name and an age

This program asks for a name and an age and prints a greeting. The StringIO that replaces the keyboard supplies "Aung" and "20" as if someone had typed them and pressed Enter, so the example finishes at once instead of waiting.

The answers come from a string, not a keyboard, so they are not echoed to the screen, and that is why the two prompts and the greeting run together on one line. In a real terminal you would see your typing after each prompt.

ask.rb
require "stringio"

# A stand-in for someone typing "Aung", Enter, "20", Enter
$stdin = StringIO.new("Aung\n20\n")

print "What's your name? "
name = gets.chomp

print "How old are you? "
age = Integer(gets.chomp)

puts "Hello, #{name}. Next year you will be #{age + 1}."

Code breakdown

  1. Fake keyboard$stdin = StringIO.new("Aung\n20\n")

    Standard input is replaced by a StringIO holding two lines. Every gets in the rest of the script now reads from this string, so the program never waits for a real keyboard. Remove this line and the same script asks a human.

  2. Promptprint "What's your name? "

    print shows the prompt without a newline, so the cursor stays right after the question. With puts the cursor would drop to a new line after every prompt.

  3. Read and cleanname = gets.chomp

    gets returns "Aung\n" and chomp drops the newline, so name holds just "Aung".

  4. Convert on purposeage = Integer(gets.chomp)

    Integer("20") turns the text into the whole number 20. Text that is not a whole number raises ArgumentError, which is louder than to_i quietly giving 0.

  5. Use the valuesputs "Hello, #{name}. Next year you will be #{age + 1}."

    age is now a real Integer, so age + 1 is 21. Had it stayed text, this line would raise a TypeError.

You should see
What's your name? How old are you? Hello, Aung. Next year you will be 21.

Converting text to numbers safely

The ways of turning text into an integer look alike but treat bad input in completely different ways. The table shows the main differences, and the code after it combines them into a helper method that validates an age.

ExpressionResultWhat it tells you
"42".to_i42Fine for clean input
"abc".to_i0Fails silently and looks like a real 0
"12abc".to_i12Stops at the first bad character
Integer("12abc")ArgumentErrorRaises instead of guessing
Integer("abc", exception: false)nilYou decide what to do next
Integer("09", exception: false)nilA leading 0 means octal, and 9 is not an octal digit
Integer("09", 10)9Base 10 forces ordinary decimal
parse_age.rb
def parse_age(text)
  age = Integer(text.to_s.strip, 10, exception: false)
  age if age && age.between?(0, 150)
end

p parse_age("20")
p parse_age(" 42\n")
p parse_age("abc")
p parse_age("007")
p parse_age("-5")
p parse_age(nil)
p parse_age("200")

The values printed are 20, 42, nil, 7, nil, nil and nil. to_s turns a nil input into an empty string so nothing crashes, strip removes newlines and spaces, and base 10 reads "007" as 7. Every invalid input makes the method return nil, so the caller can decide to ask again.

When gets returns nil

Calling gets after the input has ended returns nil. The code below simulates ruby script.rb < /dev/null with an empty StringIO. Watch what chomp does on nil and which two ways protect you.

eof.rb
require "stringio"

$stdin = StringIO.new("")   # empty input, like `ruby script.rb < /dev/null`

line = gets
p line

begin
  line.chomp
rescue NoMethodError => e
  puts "#{e.class}: #{e.message}"
end

p gets&.chomp
p gets.to_s.chomp

The output has four lines: nil, NoMethodError: undefined method 'chomp' for nil, nil, and "". The wording of the message differs slightly between Ruby versions: this output comes from Ruby 4.0.9, while Ruby versions before 3.4 used a backtick as the opening quote.

gets reads files named on the command line

If you start a script as ruby notes.rb data.txt, a bare gets reads lines from data.txt, because Ruby treats extra command-line words as files. $stdin.gets always reads standard input, which is what you want for a question to the user.

Reading more than one line

When there are many lines, a while (line = gets) loop keeps reading until gets returns nil, because the loop stops as soon as the assignment produces nil. The code below skips blank lines and splits each line such as "tea 2" into a name and a count.

many_lines.rb
require "stringio"

$stdin = StringIO.new("tea 2\ncoffee 3\n\nmilk 1\n")

total = 0
while (line = gets)
  line = line.chomp
  next if line.empty?          # skip blank lines

  name, count = line.split
  total += Integer(count)
  puts "#{name}: #{count}"
end
puts "items: #{total}"

The output is tea: 2, coffee: 3, milk: 1 followed by items: 6. If you would rather not write the loop, $stdin.each_line(chomp: true) hands you each line without its newline, $stdin.readlines(chomp: true) gives an array, and $stdin.read returns everything as one string. Be careful with readline: when the input is exhausted it raises EOFError instead of returning nil.

An interactive script for a real terminal

Here is the complete program without any StringIO. Run it in a terminal with ruby ask_age.rb and type your answer. Thanks to gets&.chomp it does not crash when there is no input at all (for example with < /dev/null) and prints a message instead, and when you type something that is not a whole number, Integer returns nil, so a plain if can tell the two cases apart.

ask_age.rb
print "How old are you? "
input = gets&.chomp

if input.nil?
  puts "\nNo input received."
else
  age = Integer(input, 10, exception: false)
  if age
    puts "Next year you will be #{age + 1}."
  else
    puts "#{input.inspect} is not a whole number."
  end
end

Printing "\nNo input received." when there is no input moves the cursor to a fresh line after the prompt. Try the script in your own terminal with 20, then abc, then Ctrl-D (Ctrl-Z followed by Enter on Windows), one at a time.

In real projects

Where this shows up in real projects

Command-line tools are where gets lives. Small scripts that filter a log (cat access.log | ruby slow_requests.rb), setup wizards that ask for a project name, and rake tasks that ask for confirmation all read standard input. Because those scripts also run from cron jobs and CI servers where nobody is typing, a missing line is a normal situation to handle, not a rare accident, and $stdin.tty? lets a script check whether a human is attached.

The same habits protect web applications. A form field, a query string and a JSON body are all text that arrives from outside, so the clean, convert-on-purpose, validate routine you practised here with Integer(text, 10, exception: false) is the same routine a controller applies to params. And replacing $stdin with a StringIO is the same trick test suites use to feed scripted answers to interactive code.

Common mistakes

Common mistakes

1. Doing arithmetic on the raw string

age = gets.chomp followed by age + 1 raises a TypeError (no implicit conversion of Integer into String). Worse, "20" * 2 does not fail at all: it repeats the text and gives "2020". Convert with Integer(...) before you calculate.

2. Calling chomp on nil

When no input is left, gets.chomp raises NoMethodError (undefined method 'chomp' for nil). Use gets&.chomp, or store the result of gets first and check for nil. Tests and pipes are where this problem shows up first.

3. Letting to_i hide bad input

"abc".to_i gives 0, so someone who types abc is recorded as being 0 years old, and the mistake never shows. Use Integer(text, 10, exception: false) and ask again when the result is nil; the base 10 keeps inputs such as "09" from being read as octal.

4. Comparing before cleaning

Checking answer == "yes" after answer = gets is false even when the user typed yes, because answer is "yes\n". "Yes" and " yes " fail the same way. Write answer.strip.downcase == "yes" instead.

Best practices

Best practices

  • Put reading and parsing in one small method such as read_age(io), so the rest of the program only sees clean values.
  • Pass the input object into the method (io = $stdin) so tests can hand it a StringIO.
  • Prefer Integer(text, 10, exception: false) and a nil check over to_i whenever a wrong answer matters.
  • Normalize yes/no style answers with strip and downcase before comparing them.

Mini challenge

Mini challenge: keep asking until the age is valid

Write a method read_age(io) that keeps reading until it gets a whole number from 0 to 120, or returns nil if the input ends. Use a StringIO as the "keyboard" so the script never blocks.

  • Read with io.gets (not Kernel#gets) so the method works with any IO object
  • Return nil when io.gets returns nil
  • Accept values such as " 42\n" and "007" (as 42 and 7) using Integer(..., 10, exception: false)
  • For anything else print "Try again." and read again
read_age.rb
require "stringio"

def read_age(io)
  # TODO: loop until a valid answer or the end of input
  # TODO: return nil when io.gets returns nil
  # TODO: accept whole numbers from 0 to 120, otherwise print the hint and ask again
end

keyboard = StringIO.new("abc\n\n150\n 42 \n")
# TODO: call read_age(keyboard) twice and print "Age: ..." each time

Expected: Try again. Try again. Try again. Age: 42 Age: no answer

Show hint

You can use return inside loop do ... end. Pass line.strip to Integer, and return the age only when it is not nil and age.between?(0, 120) is true. On the second call the input is exhausted, so nil comes back.

Show solution
read_age.rb
require "stringio"

def read_age(io)
  loop do
    line = io.gets
    return nil if line.nil?

    age = Integer(line.strip, 10, exception: false)
    return age if age && age.between?(0, 120)

    puts "Try again."
  end
end

keyboard = StringIO.new("abc\n\n150\n 42 \n")
first = read_age(keyboard)
puts "Age: #{first}"
second = read_age(keyboard)
puts "Age: #{second || 'no answer'}"

Quick quiz 1 / 3

What does gets return after the input has ended, for example with ruby script.rb < /dev/null?

Quick quiz 2 / 3

Which call returns nil instead of raising when the text is not a whole number?

Quick quiz 3 / 3

A user types yes and presses Enter. After answer = gets, what does answer == "yes" give?

What to remember

  • gets returns one String ending in a newline, or nil when input is exhausted; chomp and strip clean it.
  • gets.chomp raises NoMethodError on nil, so use gets&.chomp or check for nil.
  • Input is always text: convert it on purpose with Integer(text, 10, exception: false), because to_i hides mistakes as 0.
  • Replacing $stdin with a StringIO lets you run and test input code without a keyboard.

Official Ruby Documentation — Ruby Documentation

Updated on

Progress is saved only in this browser on this device. It isn't synced to other devices.

Report a problem with this lessonOpens your email app with this lesson's address filled in — nothing is sent until you send it.

User Input (gets) | Thuta Learning