The most beautiful line of code I have ever seen
by Pace on November 20th, 2007 @ 10:22 am in
Off-Topic
Tags: programming, ruby
The most beautiful line of code I have ever seen is the following line of Ruby code, which I snagged from the Pickaxe book:
(words[key] ||= []) << word
Granted, if you don’t think that Perl can be beautiful and elegant, you’re not likely to think that Ruby is either. But I think that the above line of code is the most beautiful, elegant, and eloquent line of code I have ever seen. Let me walk you through it.
First we have
words[key] ||= []
which is shorthand for
words[key] = words[key] || []
just like i += 2 is shorthand for i = i + 2. So what does this do? If words[key] (the result of a hashtable lookup) is non-nil, it does nothing. But if words[key] is nil (uninitialized), it initializes it to an empty array. It’s a very nice Ruby idiom for initialization.
Then it wraps up the resulting array (Ruby, like Lisp, is functional, so every expression returns a value) and appends a new word to it.
It’s equivalent to the following 4 lines of C++-ish pseudocode:
if (words.lookup(key) == null) { words.set(key, new Array()); } words.get(key).append(word);
One of the guiding principles of Ruby is that code is read more often than it is written. How lovely it is that we can end up with such elegant and eloquent results.
- Related posts:
- Has my website been hacked into sending spam?













#1 Posted by 2008 | Pace and Kyeli on October 31st, 2008 11:05 pm | link
[...] November, Pace had fun with Ruby and Rails while working half-time as C9’s CTO. (She had not so much fun being a sysadmin, [...]