DEV Community

Cover image for Hashes with default procs
Oliver
Oliver

Posted on • Updated on • Originally published at codeandclay.com

Hashes with default procs

Our app uses a list of bird names.

bird_names = %w(
  redbreast
  crow
  eagle
  hedge-sparrow
  sparrow
  pigeon
  owl
  penguin
)
Enter fullscreen mode Exit fullscreen mode

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"
}
Enter fullscreen mode Exit fullscreen mode

We treat the hash as a proc.

> bird_names.map &bird_names_and_modern_equivalents
Enter fullscreen mode Exit fullscreen mode

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]
Enter fullscreen mode Exit fullscreen mode

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 = Proc.new { |_h, k| k }
Enter fullscreen mode Exit fullscreen mode
> bird_names.map &bird_names_and_modern_equivalents
=> ["robin", "crow", "eagle", "dunnock", "sparrow", "pigeon", "owl", "penguin"]
Enter fullscreen mode Exit fullscreen mode

Top comments (2)

Collapse
 
annacruz profile image
Anna Cruz

This sample of default proc is amazingly beautiful! Thanks for sharing this!

Ps.: There's a small mistake in the last code line, you called the second hash by the wrong name

Collapse
 
codeandclay profile image
Oliver • Edited

Thank you. I've corrected the hash name.