Ruby’s Principle of Least Surprise

In his latest post, Sean is talking about his wow moments with Ruby. He refers to the Principle of Least Surprise which is one of the ideas behind Ruby.

His posted reminded me that I don’t cease to be surprised by Ruby. Of course if you know me just a little bit, you know that I’m easily surprised. I’m very naive and gullible. Because of it of course I’m often surprised. Often in a bad way.

With Ruby I’m often surprised too, but in a good way. Maybe Matz meant Principle of Least *Bad* Surprise?

I must admit also that my brain is half rotten by all of those years of C/C++/Java. A year or so ago, I started the process of cleaning it up by doing things in Lisp and even a little bit of Python, trying to save the 3 last neurons left. (yes, I have 6 neurons)

It’s all good but nothing like trying to solve real problems, to actually get stuff.

The surprises I have with Ruby (and Rails) are similar to the surprises I had and still have with the Mac. Like with the Mac, I now expect to be (happily) surprised. BTW, can you say you’re surprised if you expect to be surprised?

When I switched to the Mac I didn’t know how to install applications, because I couldn’t get over the fact that all I had to do was to drag an icon from here to there. That could never work, and I didn’t know what the real way was.

I was very excited (though surprised) to discover that yes, it was that easy.

The other day I had to loop through a collection of numbers and add them up. Bad Java programmer that I am, my first instinct was to do:

  def calc_sum(elements)
    sum = 0
    elements.each do |n|
      sum += n.value
    end
    sum
  end
  

Oh I knew this was bad, I knew it because of the strong odor. I just didn’t know what the good alternative was. I expected some good surprise though. (again, expecting to be surprised)

A better, more Ruby way is:

  def calc_sum(elements)
    elements.inject {|sum,n| sum+n}
  end
  

Whoa! Now, that feels great. Well, at least less Java. Then Rails comes along and makes the surprisingly elegant Ruby even better, by providing a sum method to Enumerable.

  def calc_sum(elements)
     elements.sum {|n| n.value}
  end
  

Whoa! I love it!! Least Surprise my ass.

1 Comment »

  1. Jeffrey Fredrick said,

    March 5, 2007 @ 9:56 pm

    Heh.

    That was my favorite part of programming in Ruby/Rails. Every time I’d write something it would work but my Java background would be hanging out in the breeze.

    Then I’d rewrite it and it would be smaller and easier to read.

    Repeat.

    Cool!

RSS feed for comments on this post · TrackBack URI

Leave a Comment