Hashes with default procs
Oliver

Oliver @codeandclay

About: Audio editor by day. Rubyist by night. Had a brief sojourn as a junior dev five years ago. Looking to switch careers again.

Location:
UK
Joined:
Aug 21, 2018

Hashes with default procs

Publish Date: Jan 21 '23
4 2

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

Comments 2 total

  • Anna Cruz
    Anna CruzFeb 3, 2023

    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

    • Oliver
      OliverFeb 3, 2023

      Thank you. I've corrected the hash name.

Add comment