Why I Like Ruby More Every Day

September 28, 2006

I’ve jumped back into Ruby codin’ lately for a few personal projects and prototypes that I’ve been working on, and I just find, more and more – that one of the reasons why I love Ruby so much is that it really seems to have the developer in mind. Java seems very disinterested in the developer, and interested in, well, verbosity?

For example, I ran into a very simple situation where I have a Map (call it what you will, HashMap, Hashtable, Hash, whatever) that I needed to reverse – or invert. In essence, what I needed was a new Map whereby the keys became the values and the values became the keys.

Now, in Java (assuming I have the privilege of Java 5), I would do something like this:

    HashMap inverse = new HashMap();
for ( Map.Entry me : existingMap.keySet() ){
inverse.put( me.getValue(), me.getKey() );
}

If I did not have the privilege of Java 5, it would look something like this:

    HashMap inverse = new HashMap();
for ( Iterator i = existingMap.keySet().iterator(); i.hasNext(); ){
Map.Entry me = (Map.Entry) i.next();
inverse.put( me.getValue(), me.getKey() );
}

Let us contrast this with Ruby:

    inverse = existingMap.invert

Now, excuse me while I got make a fresh cup of coffee with all the time I just saved.


Hierarchy: previous, next