Ever have to map all the keys of a Hash, or Hash-like Ruby object? For example, you have a Hash mapping keys to the binary contents of several files, and you want to present those file contents as Base64.
Imagine we have a Hash that looks something like this:
pictures_hash = { 'goblins' => PICTURE_OF_GOBLINS, 'kittens' => PICTURE_OF_KITTENS }
If you were just doing this mapping inline, it might look like this:
pictures_hash.inject({}) do |accumulate, (key, binary)| accumulate[key] = Base64.encode64(binary) accumulate end
Instead of typing out almost-identical code over and over again, here’s an implementation as a simple block-receiving method on Hash itself.
class Hash def map_values inject(self.dup) do |a, (k,v)| a[k] = yield(v) a end end end
Now the code to Base64 encode the file contents becomes this much simpler snippet.
pictures_hash.map_values do |binary| Base64.encode64(binary) end
Leave a Comment