Code & Clay – Notes to self. Mainly Ruby/Rails.

Hashes with default procs

Our app uses a list of bird names.

bird_names = %w(

One day, someone mentions that a couple of the birds – the redbreast and hedge-sparrow – are now more commonly known as the robin and dunnock. Not wanting to confuse our users, we decide we should use the modern vernacular.

Instead of going back and changing the data we can create a new list of bird names – updating any names that have changed with their modern equivalents.

We pair the old with the new names in a hash.

bird_names_and_modern_equivalents = {
  "redbreast" => "robin",
  "hedge-sparrow" => "dunnock"

As in the previous post, we treat the hash as a proc.

> &bird_names_and_modern_equivalents

The result isn’t quite what we want. We have the new names for the redbreast and the dunnock but all the other birds are now nil.

=> ["robin", nil, nil, "dunnock", nil, nil, nil, nil]

We want our list to contain the original names if there are no substitions in our hash.

Just as we can set a default hash value, we can also set a default proc.

Below, if we ask the hash for the value of a key that doesn’t exist, it returns the value of the default proc instead. In this case, it returns the name of the bird we asked for unchanged.

bird_names_and_modern_equivalents.default_proc = { |_h, k| k }
> &bird_names_and_modern_equivalents
=> ["robin", "crow", "eagle", "dunnock", "sparrow", "pigeon", "owl", "penguin"]

If you really want to get to grips with Ruby development and gain a solid understanding of Object Oriented Design, I thoroughly recommend Sandi Metz's Practical Object Oriented Design in Ruby. It's the perfect introduction to OOP and pragmatic Ruby. You can buy it here.

“Meticulously pragmatic and exquisitely articulate, Practical Object Oriented Design in Ruby makes otherwise elusive knowledge available to an audience which desperately needs it. The prescriptions are appropriate both as rules for novices and as guidelines for experienced professionals.”

Katrina Owen, Creator, Exercism

Essential Reading: Learn Rails 6