Brevity and Readability

So I’m cruising along in Ruby one day, when all at once I realize I’ve stopped writing. I’m stuck. I needed to compare two arrays, and trim one so that any records in it would be removed if they existed in the other one. In PHP, one way to do this would be to loop through one array and use something like in_array to check the items in the current loop against those in the other array. This approach always felt a little verbose to me, and I was hesitant to just hack up an equivalent in Ruby.

After a little digging in the manual and perusing a few conversations, I ended up with something that might look like this:

@people.delete_if { |person| @roster.include?(person) } #short and sweet!

I gotta admit – as much as I love brevity, that is almost too short. The nice thing about some of these common control structures, and for that matter functions that are named like in_array, is that if you are careful you can write code that is almost self-documenting.

foreach ($roster as $participant) {
 
	if ($found_participant = array_search($participant, $people)) {
 
	    unset($people[$found_participant])
 
	}
 
}

That is, if you asked a stranger to just read the words in the passage above out loud to themselves, chances are they will be able to figure it out. I’m not so sure that’s the case with that beautiful little line of Ruby. Maybe it’s just me and my relative inexperience.

Speaking of readability, Henrik Nyh has a nice little piece on making your function calls more readable in Ruby.

One Trackback/Pingback

  1. [...] of array functions in PHP, ExpressionEngine developer Derek Jones shares a trick for remembering which order to send [...]

Post a Comment

Your email is never published nor shared. Required fields are marked *
*
*

You can follow any discussion on this article with the RSS feed for this post.

About this article

Green Galoshes is a weblog written by Justin D. Henry. This entry was published on or around February 6, 2008.

Categories & Tags

This article is filed under art, code, reference. It is further described as , , , , , , , .