End of Life Ruby 3.1 has reached end of life and gets no more fixes. Switch to Ruby 4.0 →
IO#gets
static VALUE
rb_io_gets_m(int argc, VALUE *argv, VALUE io)
{
VALUE str;
str = rb_io_getline(argc, argv, io);
rb_lastline_set(str);
return str;
}
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:
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:
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:
# 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, ornilif none. -
But returns no more than
limit+1bytes.
For all forms above, trailing optional keyword arguments may be given; see Getline Options:
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
-
3.0
-
IO#wait_readable,IO#wait_writable,IO#read,IO#writeand other related methods (e.g.IO#puts,IO#gets) may invoke the scheduler hook io_wait(io, events, timeout) in a non-blocking execution context. [Feature #16786]
-