Reverting Ruby Hash So That Array Values Become Keys, And Keys become Values


Dale Emery @dhemery ask this question on Twitter. I responded with Gist solution.

The Problem

As a software tester, I asked for data as an example for input for this problem (note the Imagine word, which suggests that I needed to create a model of Dale’s explanation):

The Solution

Code Review

Second line is result container, empty at the start.

Third line does the actual work. Map function works on Hash. Hash is the input for reverse_birthdays. Map takes every Hash pair (day, names), and modifies it. Note the idiom |day,names|. I often see something like |k,v|, which is shorthand for |key,value|. It is better to use names what key and value represent, in this case, day and names. Plural indicates Array. So code takes every (day, names) pair, then for every names Array, takes every name in that Array using map function and creates new result Hash element that has for key name, and for value day.

Fourth line returns resulting hash.

Sixth line is data input, explained by Dale in his Tweet. Variable actual to denote original data. Ruby Hash is data sets of key, value pairs. In this example, values are assigned to key with =>, and Hash is denoted with { }. Array values are denoted with [ ]. In Python, Hash is called Dictionary, in Elixir it is map.

Seventh line is expected result, reverse Hash of input Hash.

Last line is a test (just joking, it is a check) for reverse_birthdays function. It returns true.

There are 5 revisions of this simple function, because while I was writing this post, I realized that first version returned Array of Hashes, instead of one Hash. Click revisions, and you will see the evolution of reverse_birthdays functions.

Originally published at tentamen software testing blog.

Founder of Tentamen, software testing agency.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store