Kernel#gets

gets(sep=$/) -> string or nil
Returns: String or nil · Updated March 13, 2026 · Kernel Methods
input io console stdin

gets reads the next line from standard input (STDIN), returning it as a string with the line separator removed. At end of file, it returns nil. This method is commonly used for interactive command-line programs that need to read user input.

Syntax

gets(sep=$/)

Parameters

ParameterTypeDefaultDescription
sepString$/ (newline)The line separator. When specified, gets reads until it encounters this string.

Examples

Basic usage

# Simulating user input with StringIO
require 'stringio'

input = StringIO.new("Hello\nWorld\n")
$stdin = input

first_line = gets
puts first_line.inspect  # => "Hello\n"

second_line = gets
puts second_line.inspect # => "World\n"

third_line = gets
puts third_line.inspect  # => nil

$stdin = STDIN  # Restore stdin

Reading with custom separator

require 'stringio'

input = StringIO.new("one,two,three\n")
$stdin = input

# Read until comma instead of newline
line = gets(",")
puts line.inspect  # => "one,two,three\n"

$stdin = STDIN

Common Patterns

Interactive input loop

puts "Enter your name:"
name = gets
puts "Hello, #{name.chomp}!"

Chomp before using

# Always chomp to remove the trailing newline
print "Enter command: "
cmd = gets.chomp

if cmd == "exit"
  puts "Goodbye!"
  exit
end

Errors

  • IOError: If STDIN is closed, gets returns nil rather than raising an error.
  • ArgumentError: Raised if the separator is an empty string (Ruby 3.0+).

See Also