Skip to content

Preview Ruby 4.1 is a preview. It can change before the final release. Switch to Ruby 4.0 →

instance method

IO#gets

(::string? sep, ?::int limit, ?chomp: ::boolish) -> ::String?
(?::int limit, ?chomp: ::boolish) -> ::String?
gets(sep = $/, chomp: false) → string or nil
gets(limit, chomp: false) → string or nil
gets(sep, limit, chomp: false) → string or nil

Reads and returns a line from the stream; assigns the return value to $_. See Line IO.

With no arguments given, returns the next line as determined by line separator $/, or nil if none:

Example
f = File.open('t.txt')
f.gets # => "First line\n"
$_     # => "First line\n"
f.gets # => "\n"
f.gets # => "Fourth line\n"
f.gets # => "Fifth line\n"
f.gets # => nil
f.close

With only string argument sep given, returns the next line as determined by line separator sep, or nil if none; see Line Separator:

Example
f = File.new('t.txt')
f.gets('l')   # => "First l"
f.gets('li')  # => "ine\nSecond li"
f.gets('lin') # => "ne\n\nFourth lin"
f.gets        # => "e\n"
f.close

The two special values for sep are honored:

Example
f = File.new('t.txt')
# Get all.
f.gets(nil) # => "First line\nSecond line\n\nFourth line\nFifth line\n"
f.rewind
# Get paragraph (up to two line separators).
f.gets('')  # => "First line\nSecond line\n\n"
f.close

With only integer argument limit given, limits the number of bytes in the line; see Line Limit:

Example
# No more than one line.
File.open('t.txt') {|f| f.gets(10) } # => "First line"
File.open('t.txt') {|f| f.gets(11) } # => "First line\n"
File.open('t.txt') {|f| f.gets(12) } # => "First line\n"

With arguments sep and limit given, combines the two behaviors (see Line Separator and Line Limit).

Optional keyword argument chomp specifies whether line separators are to be omitted:

Example
f = File.open('t.txt')
# Chomp the lines.
f.gets(chomp: true) # => "First line"
f.gets(chomp: true) # => "Second line"
f.gets(chomp: true) # => ""
f.gets(chomp: true) # => "Fourth line"
f.gets(chomp: true) # => "Fifth line"
f.gets(chomp: true) # => nil
f.close

Ruby version changes

  1. 3.0
See also #getpass #goto #getch #goto_column also in 4.0 · 3.4 · 3.3 · 3.2 · 3.1 · 3.0