Ruby Map Array to Hash

map-array-to-hash

Sometimes you need to map array value to a hash structure. It could be that you have a set of keys, and you want to map some values related to those keys to a hash in order to return it from a function. Or something else, what do I know. But I do know a nice, clean way to do it:

As they say: The below example is a little basic – but it should still show the gist of it.

lookup_table = { arms: 15, legs: 25, head: 42, ... etc, etc. }
keys = %w'arms legs'
Hash[keys.map{ |key| [key.to_sym, lookup_table[key]] }]

And now we have mapped our array to a hash.

With the lookup table in this code, we could have of course just extracted a subset of our lookup_table. But what if it wasn’t such a convenient lookup_table? What if it was methods defined on another class that we want to extract values from? Or database values? For this case, the above little trick of initialising a Hash can come quite in handy once in a while.