liveBook · Manning

Gets

As explained in The Well-Grounded Rubyist, Fourth Edition

gets is a Ruby input method that reads the next line from a file or other input stream and returns nil at end of input.

gets reads the next line from keyboard input or another input stream. It returns the line as input data and returns nil when no more input remains. section 1.1.7 section 12.2.2

Read and convert a temperature

print "Hello. Please enter a Celsius value: " celsius = gets fahrenheit = (celsius.to_i * 9 / 5) + 32 puts "The Fahrenheit equivalent is #{fahrenheit}." gets supplies the input; to_i converts the received line before the arithmetic runs.

Choose the related operation according to the unit of input and the desired end-of-input behavior:

  • Use gets for one line at a time from a file or input stream. section 12.2.2
  • Use getc for one character; unlike a bare gets call, getc names its input stream explicitly. section 12.1.4
  • Use readline when reaching end of file should raise an EOFError instead of returning nil. section 12.2.2
  • Use readlines for all lines as an array, or each and each_line to process a File line by line. section 12.2.2
>> f.gets
=> "class Ticket\n"
>> f.gets
=> "  def initialize(venue, date)\n"
>> f.gets
=> "    @venue = venue\n"

An irb-sized sequence shows gets advancing through successive lines of a File object. 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)

An end-of-file comparison makes gets returning nil directly observable beside readline raising EOFError. section 12.2.2

How The Well-Grounded Rubyist, Fourth Edition covers it

How deep it goes
Explains line reads, stream selection, sequential position, and nil at end of input; defers broader I/O operations.
Examples
Demonstrates a Celsius converter, irb reads from a File object, and end-of-file comparison with readline.
What it assumes
Assumes familiarity with to_i while introducing keyboard input through a concrete temperature-conversion task.
What you can do after
Apply it via Ruby programs that accept lines interactively or process files sequentially.
How it connects
Connects keyboard input, file I/O, input streams, getc, readline, readlines, and File enumeration.

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.