My Life As A Blog

Ruby Tuesday #5 : Hello World

leave a comment »

The obvious first thing to do with a new programming language is a Hello World exercise. (If you want to know how to do Hello World in a variety of ways, follow this link.) A simple Hello World in Ruby is trivial (I used it to test my installation of Ruby here):

puts "Hello World"

Trouble with that example is we don’t learn a whole lot about Ruby. So, I figured I’d stick with a Hello World, but instead of outputting to the screen, I’d output a tweet. Twitter has an API (documented here) that should enable me to tweet via a Ruby program.

To start down this path, I figured it made sense to start with something relatively straightforward – download the public timeline. Here’s a function that takes an address and returns the response from that address:

require 'net/http'

def getUrl(address)
 url = URI.parse(address)
 req =
 res = Net::HTTP.start(, url.port) {|http| http.request(req)}

The interesting thing about the first line is that require isn’t a language keyword, it’s a method (defined in kernel.) Because the syntax of Ruby doesn’t require parentheses it looks like a keyword – which means that Ruby is naturally set up for this kind of extension, meaning fluent APIs and DSLs are natural in Ruby.

To call that function and output the resulting data (which given the url I’m using will be in XML format), use the following code:

puts getUrl('')

So, downloading the public timeline turns out to be fairly straightforward – although I’m not yet handling error cases like there being no connection. But the output is a bunch of XML. So, my next task will be to process the XML into something friendlier.


Written by remark

May 13, 2008 at 7:03 pm

Posted in Development, Ruby, Software

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

%d bloggers like this: