<ppdoc>
<copyright>
Copyright (c) 2001 by Addison Wesley Longman, Inc. This material may
be distributed only subject to the terms and conditions set forth in
the Open Publication License, v1.0 or later (the latest version is
presently available at http://www.opencontent.org/openpub/).
<p/>
Distribution of substantively modified versions of this document is
prohibited without the explicit permission of the copyright holder.
<p/>
Distribution of the work or derivative of the work in any standard
(paper) book form is prohibited unless prior permission is obtained
from the copyright holder.
</copyright>
<chapter  ref="xref-000001" name="Basic Input and Output">
<p/>
Ruby
provides what at first sight looks like two separate sets of I/O
routines.  The first is the simple interface---we've been using it
pretty much exclusively so far.
<p/>
<codefragment>
<alltt><fullcode><![CDATA[  print "Enter your name: "
  name = gets
]]></fullcode>
print<nbsp/>"Enter<nbsp/>your<nbsp/>name:<nbsp/>"
name<nbsp/>=<nbsp/>gets
</alltt>
</codefragment>
<p/>
There are a whole set of I/O-related methods implemented in the
<modulename>Kernel</modulename> module---<meth>gets</meth>, <meth>open</meth>, <meth>print</meth>,
<meth>printf</meth>, <meth>putc</meth>, <meth>puts</meth>, <meth>readline</meth>,
<meth>readlines</meth>, and <meth>test</meth>---that make it simple and
convenient to write straightforward Ruby programs. These methods
typically do I/O to standard input and standard output, which makes
them useful for writing filters. You'll find them documented starting
on page 411.   
<p/>
The second way, which gives you a lot more control, is to use <classname>IO</classname>
objects.
<section>What Is an IO Object?</section>
<p/>
Ruby defines a single base class, <classname>IO</classname>, to handle input and output.
This base class is subclassed by classes <classname>File</classname> and
<classname>BasicSocket</classname> to provide more specialized behavior, but the
principles are the same throughout. An <classname>IO</classname> object is a bidirectional
channel between a Ruby program and some external resource.<footnote>For those
who just have to know the implementation details, this means that a
single <classname>IO</classname> object can sometimes be managing more than one operating
system file descriptor. For example, if you open a pair of pipes, a
single <classname>IO</classname> object contains both a read pipe and a write pipe.</footnote>
There may be more to an <classname>IO</classname> object than meets the eye, but in the
end you still simply write to it and read from it.
<p/>
In this chapter, we'll be concentrating on class <classname>IO</classname> and its most
commonly used subclass, class <classname>File</classname>. For more details on using the
socket classes for networking, see the section beginning on page 469.
<section>Opening and Closing Files</section>
<p/>
As you might expect, you can create a new file object using
<ccm><file>file</file><front>File</front><back>new</back><mref>new</mref></ccm>.
<p/>
<codefragment>
<alltt><fullcode><![CDATA[  aFile = File.new("testfile", "r")

  # ... process the file

  aFile.close
]]></fullcode>
aFile<nbsp/>=<nbsp/>File.new("testfile",<nbsp/>"r")
<p/>
#<nbsp/>...<nbsp/>process<nbsp/>the<nbsp/>file
<p/>
aFile.close
</alltt>
</codefragment>
<p/>
You can create a <classname>File</classname> object that is open for reading, writing, or
both, according to the mode string (here we opened ``<tt>testfile</tt>'' for
reading with an ``<tt>r</tt>'').  The full list of allowed modes appears
on page 326.  You can also optionally specify file
permissions when creating a file; see the description of
<ccm><file>file</file><front>File</front><back>new</back><mref>new</mref></ccm> on page 303 for details.  After opening
the file, we can work with it, writing and/or reading data as needed.
Finally, as responsible software citizens, we close the file, ensuring
that all buffered data is written and that all related resources are
freed.
<p/>
But here Ruby can make life a little bit easier for you. The method
<ccm><file>file</file><front>File</front><back>open</back><mref>open</mref></ccm> also opens a file. In regular use, it behaves just
like <ccm><file>file</file><front>File</front><back>new</back><mref>new</mref></ccm>.
However, if there's a block associated with the
call, <meth>open</meth> behaves differently. Instead of returning a new
<classname>File</classname> object, it invokes the block, passing the
newly opened <classname>File</classname> as a parameter. When the block exits, the file
is automatically closed.
<p/>
<codefragment>
<alltt><fullcode><![CDATA[  File.open("testfile", "r") do |aFile|

  # ... process the file

  end
]]></fullcode>
File.open("testfile",<nbsp/>"r")<nbsp/>do<nbsp/>|aFile|
<p/>
#<nbsp/>...<nbsp/>process<nbsp/>the<nbsp/>file
<p/>
end
</alltt>
</codefragment>
<section>Reading and Writing Files</section>
<p/>
The same methods that we've been using for ``simple'' I/O are available 
for all file objects. So, <meth>gets</meth> reads a line from standard
input, and <tt>aFile.gets</tt> reads a line from the file object
<tt>aFile</tt>.
<p/>
However, I/O objects enjoy an additional set of access methods, 
all intended to make our lives easier.
<subsection>Iterators for Reading</subsection>
<p/>
As well as using the usual loops to read data from an <classname>IO</classname> stream,
you can also use various Ruby iterators.  <cim><file>io</file><front>IO</front><back>each_byte</back><mref>each_byte</mref></cim> invokes a
block with the next 8-bit byte from the <classname>IO</classname> object (in this case,
an object of type <classname>File</classname>).
<p/>
<codefragment>
<alltt><fullcode><![CDATA[aFile = File.new("testfile")
aFile.each_byte {|ch| putc ch; putc ?. }
]]></fullcode>
aFile<nbsp/>=<nbsp/>File.new("testfile")
aFile.each_byte<nbsp/>{|ch|<nbsp/>putc<nbsp/>ch;<nbsp/>putc<nbsp/>?.<nbsp/>}
</alltt>
</codefragment>
<em>produces:</em>
<codefragment><alltt>
T.h.i.s.<nbsp/>.i.s.<nbsp/>.l.i.n.e.<nbsp/>.o.n.e.
.T.h.i.s.<nbsp/>.i.s.<nbsp/>.l.i.n.e.<nbsp/>.t.w.o.
.T.h.i.s.<nbsp/>.i.s.<nbsp/>.l.i.n.e.<nbsp/>.t.h.r.e.e.
.A.n.d.<nbsp/>.s.o.<nbsp/>.o.n.......
.
</alltt>
</codefragment>
<p/>
<cim><file>io</file><front>IO</front><back>each_line</back><mref>each_line</mref></cim> calls the block with the next line from the file.
In the next example, we'll make the original newlines visible using
<cim><file>string</file><front>String</front><back>dump</back><mref>dump</mref></cim>, so you can see that we're not cheating.
<p/>
<codefragment>
<alltt><fullcode><![CDATA[!-aFile = File.new("testfile")
aFile.each_line {|line| puts "Got #{line.dump}" }
]]></fullcode>
aFile.each_line<nbsp/>{|line|<nbsp/>puts<nbsp/>"Got<nbsp/>#{line.dump}"<nbsp/>}
</alltt>
</codefragment>
<em>produces:</em>
<codefragment><alltt>
Got<nbsp/>"This<nbsp/>is<nbsp/>line<nbsp/>one\n"
Got<nbsp/>"This<nbsp/>is<nbsp/>line<nbsp/>two\n"
Got<nbsp/>"This<nbsp/>is<nbsp/>line<nbsp/>three\n"
Got<nbsp/>"And<nbsp/>so<nbsp/>on...\n"
</alltt>
</codefragment>
<p/>
You can pass <meth>each_line</meth> any sequence of characters as a line
separator, and it will break up the input accordingly, returning
the line ending at the end of each line of data. That's why you see
the ``<tt>\n</tt>'' characters in the output of the previous example.
In the next example, we'll use ``<tt>e</tt>'' as the line separator.
<p/>
<codefragment>
<alltt><fullcode><![CDATA[!-aFile = File.new("testfile")
aFile.each_line("e") do |line|
  puts "Got #{ line.dump }"
end
]]></fullcode>
aFile.each_line("e")<nbsp/>do<nbsp/>|line|
<nbsp/><nbsp/>puts<nbsp/>"Got<nbsp/>#{<nbsp/>line.dump<nbsp/>}"
end
</alltt>
</codefragment>
<em>produces:</em>
<codefragment><alltt>
Got<nbsp/>"This<nbsp/>is<nbsp/>line"
Got<nbsp/>"<nbsp/>one"
Got<nbsp/>"\nThis<nbsp/>is<nbsp/>line"
Got<nbsp/>"<nbsp/>two\nThis<nbsp/>is<nbsp/>line"
Got<nbsp/>"<nbsp/>thre"
Got<nbsp/>"e"
Got<nbsp/>"\nAnd<nbsp/>so<nbsp/>on...\n"
</alltt>
</codefragment>
<p/>
If you combine the idea of an iterator with the auto-closing block
feature, you get <ccm><file>io</file><front>IO</front><back>foreach</back><mref>foreach</mref></ccm>. This method takes the name of an
I/O source, opens it for reading, calls the iterator once for every
line in the file, and then closes the file automatically.
<p/>
<codefragment>
<alltt><fullcode><![CDATA[IO.foreach("testfile") { |line| puts line }
]]></fullcode>
IO.foreach("testfile")<nbsp/>{<nbsp/>|line|<nbsp/>puts<nbsp/>line<nbsp/>}
</alltt>
</codefragment>
<em>produces:</em>
<codefragment><alltt>
This<nbsp/>is<nbsp/>line<nbsp/>one
This<nbsp/>is<nbsp/>line<nbsp/>two
This<nbsp/>is<nbsp/>line<nbsp/>three
And<nbsp/>so<nbsp/>on...
</alltt>
</codefragment>
<p/>
Or, if you prefer, you can retrieve an entire file into an array of
lines:
<p/>
<codefragment>
<fullcode><![CDATA[arr = IO.readlines("testfile")
arr.length
arr[0]
]]></fullcode><rubycode>
<tr>
<td colspan="3"><tt>arr<nbsp/>=<nbsp/>IO.readlines("testfile")</tt></td>
</tr>
<tr>
  <td><tt>arr.length</tt></td>
  <td>&#187;</td>
  <td><tt>4</tt></td>
</tr>
<tr>
  <td><tt>arr[0]</tt></td>
  <td>&#187;</td>
  <td><tt>"This<nbsp/>is<nbsp/>line<nbsp/>one\n"</tt></td>
</tr>
</rubycode>
<p/>
</codefragment>
<p/>
Don't forget that I/O is never certain in an uncertain
world---exceptions will be raised on most errors, and you should be
ready to catch them and take appropriate action.
<subsection>Writing to Files</subsection>
<p/>
So far, we've been merrily calling <meth>puts</meth> and <meth>print</meth>,
passing in any old object and trusting that Ruby will do the right
thing (which, of course, it does). But what exactly <em>is</em> it doing?
<p/>
The answer is pretty simple. With a couple of exceptions, every object 
you pass to <meth>puts</meth> and <meth>print</meth> is converted to a string
by calling that object's <meth>to_s</meth> method. If for some reason
the <meth>to_s</meth> method doesn't return a valid string, a string is
created containing the object's class name and id, something like
<tt>&lt;ClassName:0x123456&gt;</tt>.
<p/>
The exceptions are simple, too. The <tt>nil</tt> object will print as the
string ``nil,'' and an array passed to <meth>puts</meth> will be written
as if each of its elements in turn were passed separately to
<meth>puts</meth>.
<p/>
What if you want to write binary data and don't want Ruby messing
with it?
Well, normally you can simply use <cim><file>io</file><front>IO</front><back>print</back><mref>print</mref></cim> and pass
in a string containing the bytes to be written. However, you can
get at the low-level input and output routines if you really
want---have a look at the documentation for <cim><file>io</file><front>IO</front><back>sysread</back><mref>sysread</mref></cim> and
<cim><file>io</file><front>IO</front><back>syswrite</back><mref>syswrite</mref></cim> on page 335.
<p/>
And how do you get the binary data into a string in the first place?
The two common ways are to poke it in byte by byte or to use
<cim><file>array</file><front>Array</front><back>pack</back><mref>pack</mref></cim>.
<p/>
<codefragment>
<fullcode><![CDATA[  str = ""
  str << 1 << 2 << 3

  [ 4, 5, 6 ].pack("c*")
]]></fullcode><rubycode>
<tr>
  <td><tt>str<nbsp/>=<nbsp/>""</tt></td>
  <td>&#187;</td>
  <td><tt>""</tt></td>
</tr>
<tr>
  <td><tt>str<nbsp/>&lt;&lt;<nbsp/>1<nbsp/>&lt;&lt;<nbsp/>2<nbsp/>&lt;&lt;<nbsp/>3</tt></td>
  <td>&#187;</td>
  <td><tt>"\001\002\003"</tt></td>
</tr>
<tr>
<td colspan="3"><tt></tt></td>
</tr>
<tr>
  <td><tt>[<nbsp/>4,<nbsp/>5,<nbsp/>6<nbsp/>].pack("c*")</tt></td>
  <td>&#187;</td>
  <td><tt>"\004\005\006"</tt></td>
</tr>
</rubycode>
<p/>
</codefragment>
<subsubsection>But I Miss My C++ Iostream</subsubsection>
<p/>
Sometimes there's just no accounting for taste...However, just as you can append an object to an <classname>Array</classname> using the
<meth>&lt;&lt;</meth> operator, you can also append an object to an output <classname>IO</classname>
stream:
<p/>
<codefragment>
<alltt><fullcode><![CDATA[  endl = "\n"
  $stdout << 99 << " red balloons" << endl
]]></fullcode>
endl<nbsp/>=<nbsp/>"\n"
$stdout<nbsp/>&lt;&lt;<nbsp/>99<nbsp/>&lt;&lt;<nbsp/>"<nbsp/>red<nbsp/>balloons"<nbsp/>&lt;&lt;<nbsp/>endl
</alltt>
</codefragment>
<em>produces:</em>
<codefragment><alltt>
99<nbsp/>red<nbsp/>balloons
</alltt>
</codefragment>
<p/>
Again, the <meth>&lt;&lt;</meth> method uses <meth>to_s</meth> to convert its
arguments to strings before sending them on their merry way.
<section>Talking to Networks</section>
<p/>
Ruby is fluent in most of the Internet's protocols, both low-level and
high-level.
<p/>
For those who enjoy groveling around at the network level, Ruby
comes with a set of classes in the socket library (documented starting 
on page 469). These classes give you access to TCP, UDP, SOCKS, and
Unix domain sockets, as well as any additional socket types supported
on your architecture. The library also provides helper classes to make
writing servers easier. Here's a simple program that gets information
about the ``oracle'' user on our local machine using the finger
protocol. 
<p/>
<codefragment>
<alltt><fullcode><![CDATA[  require 'socket'
  client = TCPSocket.open('localhost', 'finger')
  client.send("oracle\n", 0)    # 0 means standard packet
!-  l = client.readlines
!-  l.shift while l[0] !~ /^Login/
!-  puts l
#  puts client.readlines
  client.close
]]></fullcode>
require<nbsp/>'socket'
client<nbsp/>=<nbsp/>TCPSocket.open('localhost',<nbsp/>'finger')
client.send("oracle\n",<nbsp/>0)<nbsp/><nbsp/><nbsp/><nbsp/>#<nbsp/>0<nbsp/>means<nbsp/>standard<nbsp/>packet
puts<nbsp/>client.readlines
client.close
</alltt>
</codefragment>
<em>produces:</em>
<codefragment><alltt>
Login:<nbsp/>oracle<nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/>			Name:<nbsp/>Oracle<nbsp/>installation
Directory:<nbsp/>/home/oracle<nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/>	Shell:<nbsp/>/bin/bash
Never<nbsp/>logged<nbsp/>in.
No<nbsp/>Mail.
No<nbsp/>Plan.
</alltt>
</codefragment>
<p/>
At a higher level, the lib/net set of library modules provides
handlers for a set of application-level protocols (currently FTP,
HTTP, POP, SMTP, and telnet). These are documented starting
on page 482. For example, the following program lists the
images that are displayed on the Pragmatic Programmer home page.
<p/>
<codefragment>
<alltt><fullcode><![CDATA[     require 'net/http'

     h = Net::HTTP.new('www.pragmaticprogrammer.com', 80)
     resp, data = h.get('/index.html', nil)
     if resp.message == "OK"
       data.scan(/<img src="(.*?)"/) { |x| puts x }
     end
]]></fullcode>
require<nbsp/>'net/http'
<p/>
h<nbsp/>=<nbsp/>Net::HTTP.new('www.pragmaticprogrammer.com',<nbsp/>80)
resp,<nbsp/>data<nbsp/>=<nbsp/>h.get('/index.html',<nbsp/>nil)
if<nbsp/>resp.message<nbsp/>==<nbsp/>"OK"
<nbsp/><nbsp/>data.scan(/&lt;img<nbsp/>src="(.*?)"/)<nbsp/>{<nbsp/>|x|<nbsp/>puts<nbsp/>x<nbsp/>}
end
</alltt>
</codefragment>
<em>produces:</em>
<codefragment><alltt>
images/title_main.gif
images/dot.gif
images/dot.gif
images/dot.gif
images/aafounders_70.jpg
images/pp_cover_thumb.png
images/ruby_cover_thumb.png
images/dot.gif
images/dot.gif
</alltt>
</codefragment>
<p/>
</chapter>
</ppdoc>
