Mark Needham

Thoughts on Software Development

Ruby: Hash default value

with 2 comments

I’ve been pairing a fair bit with Ashwin this week and one thing he showed me which I hadn’t previously seen is the ability to set a default value for a hash which gets returned if we search for a key that doesn’t exist.

This is an idea that I originally came across while playing around with Clojure but with Clojure the default value was defined in the calling code rather than in the hash definition.

For example:

(def scores {:mark 10 :dave 20})
 
(get scores :tony :0)

For a similar piece of code in Ruby we could write the following:

scores = { :mark => 10, :dave => 20 }
scores.default = 0

Now if we search for a key that doesn’t exist in the hash then we’ll get the value 0:

scores[:some_other_guy]
0

We’re using this in a couple of places in our code base already but it’ll be particularly useful for an upcoming piece of functionality where we want to vary the look and feel of some pages depending on certain criteria.

For the majority of users the look and feel will remain the same but for some of them it will vary slightly. Controlling that behaviour by using a hash with some default settings therefore seems like a reasonably good fit.

Be Sociable, Share!

Written by Mark Needham

October 16th, 2010 at 2:02 pm

Posted in Ruby

Tagged with

  • I find that using the fetch method, aka: scores.fetch(:some_other_guy, 0) is a bit easier to debug. Often I find when I am trying to understand what value is coming from a hash, I look first where the hash is being accessed, not where the hash is being created. Good tip nonetheless.

  • Oh neat I didn’t know about the ‘fetch’ method. That’d certainly be useful for some situations, thanks.