Thursday, November 30, 2006

Why Ruby rocks

Just for honks & giggles, I've been messing around with rewriting/refactoring some of the code samples I've done over the years in my favorite languages to compare syntax verbosity. Ruby totally kicks ass. Consider the following method to print image filenames on disk, using most best practice conventions for indenting, bracketing, etc.:

Ruby:
def get_all_photos
    Photo.find(:all).each { |p| puts p.filename }
end

Python:
def get_all_photos():
    photos = Photo.find_all
        for p in photos:
            print p.filename

JavaScript:
function getAllPhotos() {
    var photos = Photo.find();
    for(var i=0;i<photos.length;i++) {
        document.write(p.filename);
    }
}

C#/Java:
private static void GetAllPhotos()
{
    string p = Photos.find();
    for(int i=0;i<p.Length;i++)
    {
        Console.WriteLine(p.Filename);
    }
}

Comments:
Actually for C# you can get pretty close:

static void GetAllPhotos()
{
Photo.FindAll().ForEach(delegate(Photo p) { Console.WriteLine(p.Filename); });
}
 
Actually, shorter Python would be:

def get_all_photos():
print [p.filename for p in Photo.find_all()]

Personally, I don't know why this should be called get_all_photos rather than print_photo_names... or why you would rather write short unreadable Ruby code. Like, wtf is 'lpl'?
 

Post a Comment



Links to this post:

Create a Link



<< Home

This page is powered by Blogger. Isn't yours?

Subscribe to Posts [Atom]