Refactoring with the Pickaxe

Programming Ruby, better known as the Pickaxe, the most valuable "programming book" on my shelf. Actually, it doesn’t live on my shelf, it lives on my desk. I’ve learned and used lots of languages over the years but I never remember using a reference book like this before. Ruby is an incredibly rich language and I find myself "mining" the Pickaxe looking for cool ways to fix problems and writer shorter and more readable. Here’s an example of refactoring a simple method.

Start with a hash object called params. A hash object is just a list of name, value pairs: this1 = that1, this2 = that2, etc. I have a hash object and want to build a URL query string out of it. We need to string our variables together to get something that looks like this: this1=that1&this2=that2&this3=that3. The key are joined to values with an equals sign (=), and the combined values are joined with an ampersand (&).

Here was my first crack at the code.

query = ""
params.each do | key, value |
    if (query != "") query += "&"
    query += key + "=" + value

This works, but it seems longer than necessary. So here’s take two.

query = ""
params.each { | key, value | query += (("&" if (query != "")) || "") + key + ‘=’ + value }

This code works, buts its not very readable. I wonder if there isn’t some cool Ruby method that help us clean this up. Thumbing through Pickaxe, we find that the Hash object mixes-in Enumerable, which has a method called collect that should make things easier. Hash::collect iterates over a hash, processes each item according to a block, and returns a new array – perfect. Let’s use collect to create a new array of keys joined to their values with the equals sign. After that, we can use the Array::join to join the tuples with the ampersand.

tuples = params.collect do | key, value |
  key + "=" + value
return tuples.join("&")

This can be shortened…

tuples = params.collect{ | key, value | key + "=" + value }
return tuples.join("&")

… or even shorter, and I think just as readable …

params.collect{ | key, value | key + "=" + value }.join("&")

Tags: ,


One thought on “Refactoring with the Pickaxe

Comments are closed.