Ruby Programming/Reference/Objects/IO

< Ruby Programming‎ | Reference‎ | Objects

The IO class is basically an abstract class that provides methods to use on streams (for example, open files, or open sockets).

Basically, you can call several different things on it.


Note that with 1.9, each call will return you a String with an encoding set, based on either how the connection was established, ex:

a ='some filename', 'rb:ASCII-8BIT') # strings from this will be read in as ASCII-8BIT
b ='some filename', 'r') # strings from this will be read in as whatever the Encoding.default_external is
# you can change what the encoding will be
a.set_encoding "UTF-8" # from now on it will read in UTF-8


gets reads exactly one line, or up to the end of the file/stream (and includes the trailing newline, if one was given). A blocking call.


recv(1024) reads up to at most 1024 bytes and returns your the String. A blocking call. Reads "" if a socket has been closed gracefully from the other end. It also has non blocking companions.


read reads up to the end of the file or up to the when the socket is closed. Returns any number of bytes. Blocking. For information on how to avoid blocking, see Socket.