liveBook · Manning

Readline

As explained in The Well-Grounded Rubyist, Fourth Edition

readline is a Ruby IO method that reads the next line from an input stream and raises an end-of-file error when no line is available.

readline reads the next line from a Ruby input stream, such as a File or socket. Unlike gets, it raises EOFError instead of returning nil when no line remains. section 12.2.2 section 14.5.3

Reading until a client disconnects

A chat server can place c.readline inside a loop. Each received line is broadcast; when the client disconnects, EOFError transfers control to rescue, where the connection is closed and removed. section 14.5.3

Choose related operations according to how the input stream should behave:

  • Use gets when end-of-file should produce nil rather than an exception. section 12.2.2
  • Use readlines to collect the entire file as an array of lines, or each and each_line to process lines incrementally. section 12.2.2
  • Use rewind to move the stream position back to the beginning before reading again. section 12.2.2
>> f.read
=> "  def initialize(venue, date)\n    @venue = venue\n
    @date = date\n  end\n\n
    etc.
>> f.gets
=> nil
>> f.readline
end of file reached (EOFError)

Observe gets returning nil and readline raising EOFError after the stream has reached its end. section 12.2.2

How The Well-Grounded Rubyist, Fourth Edition covers it

How deep it goes
Explains line reading, stream position, and EOFError handling, but stops short of implementation internals.
Examples
Demonstrates readline with Ruby file objects and a threaded TCP chat server.
What it assumes
Assumes familiarity with Ruby IO objects, methods, loops, and exception handling while demonstrating the EOF distinction directly.
What you can do after
Apply it in line-oriented file or socket loops, rescuing EOFError when stream closure requires cleanup.
How it connects
Contrasts gets, readlines, each_line, rewind, and EOFError while applying readline to sockets and threads.

Also explained in

Compare how 4 books explain readline →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of The Well-Grounded Rubyist, Fourth Edition. The section links point to the parts of the book it draws on.