Skip to content

End of Life Ruby 3.1 has reached end of life and gets no more fixes. Switch to Ruby 4.0 →

instance method

IO#gets

gets(sep = $/, **getline_opts) → string or nil
gets(limit, **getline_opts) → string or nil
gets(sep, limit, **getline_opts) → string or nil

Reads and returns data from the stream; assigns the return value to $_.

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 # => "This is line one.\n"
$_     # => "This is line one.\n"
f.gets # => "This is the second line.\n"
f.gets # => "This is the third line.\n"
f.gets # => nil

With string argument sep given, but not argument limit, returns the next line as determined by line separator sep, or nil if none:

Example
f = File.open('t.txt')
f.gets(' is') # => "This is"
f.gets(' is') # => " line one.\nThis is"
f.gets(' is') # => " the second line.\nThis is"
f.gets(' is') # => " the third line.\n"
f.gets(' is') # => nil

Note two special values for sep:

  • nil: The entire stream is read and returned.

  • '' (empty string): The next “paragraph” is read and returned, the paragraph separator being two successive line separators.

With integer argument limit given, returns up to limit+1 bytes:

Example
# Text with 1-byte characters.
File.open('t.txt') {|f| f.gets(1) } # => "T"
File.open('t.txt') {|f| f.gets(2) } # => "Th"
File.open('t.txt') {|f| f.gets(3) } # => "Thi"
File.open('t.txt') {|f| f.gets(4) } # => "This"
# No more than one line.
File.open('t.txt') {|f| f.gets(17) } # => "This is line one."
File.open('t.txt') {|f| f.gets(18) } # => "This is line one.\n"
File.open('t.txt') {|f| f.gets(19) } # => "This is line one.\n"

# Text with 2-byte characters, which will not be split.
File.open('t.rus') {|f| f.gets(1).size } # => 1
File.open('t.rus') {|f| f.gets(2).size } # => 1
File.open('t.rus') {|f| f.gets(3).size } # => 2
File.open('t.rus') {|f| f.gets(4).size } # => 2

With arguments sep and limit, combines the two behaviors above:

  • Returns the next line as determined by line separator sep, or nil if none.

  • But returns no more than limit+1 bytes.

For all forms above, trailing optional keyword arguments may be given; see Getline Options:

Example
f = File.open('t.txt')
# Chomp the lines.
f.gets(chomp: true) # => "This is line one."
f.gets(chomp: true) # => "This is the second line."
f.gets(chomp: true) # => "This is the third line."
f.gets(chomp: true) # => nil

Ruby version changes

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