Fun with Ruby's standard library

by Gregory Brown

It seems that I can never manage to sit through a class at my university without getting sidetracked. One of my favorite diversions is reading through Ruby's standard library, and today I decided to check out open-uri's source.

Many of us have used open-uri to open up a web page. I think it's super cool that something like open("google.com").read magically becomes possible with Tanaka Akira's library.

However, one thing I never considered was that open-uri could help us open other things too. Take a look at this.

By default, Kernel#open cannot open arbitrary things.


sandal@harmonix:~$ irb --simple-prompt
>> class A
>> def open
>> "you opened it!"
>> end
>> end
=> nil
>> open(A.new)
TypeError: can't convert A into String
from (irb):6:in `open'
from (irb):6
from :0


However, by simply requiring open-uri, you are in business!


>> require "open-uri"
=> true
>> open(A.new)
=> "you opened it!"


Now, I realize that this is far from amazing, but it's still cool to think that because a lot of ruby code is duck typed really well, you can use it for purposes other than what it is explicitly meant to do.

For the curious, open-uri will cause Kernel#open to accept arguments and a block as well, so feel free to define your open() method in your classes as you please.

So here is a little challenge for those who read this blog... Find something in the standard library that can be used in a different way than it is intended. Post it in the comments here, so people can see just how flexible Ruby really is. :)

1 Comments

Oersoep
2006-06-13 02:55:42
Funny. Zero comments, excluding this one. ;)