Shlrm.org Blog

Linux, Java, Ruby, and Politics

Ruby Input and Output

| Comments

The next chapter is one on basic input and output. This one is also kinda short. Or maybe it feels short, as there’s not a whole lot of new stuff to digest… EDIT: heh, well I started out saying it was short, but turns out I had more to say about it than I thought. Maybe I’m getting better at this blagging stuff.

An IO object in ruby is a bidirectional channel between ruby and some external resource, to almost quote the text. There’s a foot note that tells you that a single IO object may have more than one file descriptor. The text talks about how things can automatically close, but poor error handling can cause problems there. The example given is where you pass a block to the File.open method. You process the file within the block and if everything goes well, the file is autmoatically closed when the block ends. However, your file variable is scoped within that block, so if an error is thrown, you lose your file variable. You’ll end up with an IO object floating around in the heap, keeping files open, until it finally gets collected. Not really a good thing to do.

There’s a few examples on reading from files. You can read an entire file into a string, or into an array of lines. Kinda handy. Just don’t forget to rescue exceptions. Writing to files is pretty simple. You can even simulate an iostream from c++ since the << operator is set up for append in ruby. You can also include ‘stringio’ and do all your fancy file operations directly in memory on strings. Handy for when you need to submit stuff via XML-RPC or some sort of HTTP method.

Ruby comes with a set of classes in the socket library so that you can play with TCP, UDP, SOCKS, and Unix sockets. You can also deal with network goodies at a very high level. To thief a simplistic example from the book:

1
2
3
4
require 'open-uri'
open('http://pragprog.com') do |f|
  puts f.read.scan(/<img alt=".*?" src="(.*?)"/m).uniq
end

That example there shows how painfully easy it is to theif images from a website. Of course, this is a naieve example. We don’t rescue any errors or anything, but still, it works quite well. The text promises more to come in Chapter 20 about using Ruby on the interblags. I can’t wait!

Comments