January 29th, 2006

When Code Flows Like Poetry

It’s not always that you get to solve complex problems. Many a time you need to implement something—something that you know is silly enough. How do you feel? Bored, I know. However, there’s small amount of joy you get when the “tool” you use lets you be creative. (Of course, there’s a distinction between the larger problem at hand and the smallest implementable part of it; it is the typically joyless implementation of this small part that I’m talking about.)

I had a situation where I had to read a data file that had on each line data like thus:

foo:bar

Obviously, you want to hold all that data in a hash. Implementing this in a typical programming language would, in pseudocode, look something like thus:

data = file("data.txt").read
hsh = {}
foreach line in data do
        k, v = line.split(":")
        hsh["k"] = v
end

Simple enough, but boring too. With Ruby, I can play:

hsh = Hash.new
File.open("test.txt").readlines.each { |line|
        hsh = hsh.update(Hash[ *line.split(":").
                map { |ele| ele = ele.match(/(.*)\n/)[1] rescue ele }
        ])
}

The Ruby code flows like poetry. Literally. There’s an extremely elegant solution, like why pointed out to me:

Hash[*IO.read('test.txt').scan(/^(.+?):(.*)/).flatten]

But then I’d say there are no blocks there. :-)

There are many such Ruby gems scattered all around. I’ll point you to some of them I found on RedHanded:

Go use a better tool, if you can.

Posted at 03:27 pm | Link | 18 comments | Leave a comment