We've seen lots of Ruby feature requests about converting an Enumerable to a Hash: to_h
, map_hash
, map_to
, each_with_hash
, etc. Let's look at one common, simple case of this.
Building a key/value mapping from a collection of keys is awkward. We commonly see Hash[*collection.map { |element| [element, calculate(element)] }]
or collection.each_with_object({}) { |element, hash| hash[element] = calculate(element) }
. Both are verbose. They require boilerplate code that's not relevant to the programmer's intent: to associate an enumerable of keys with calculated values.
Ruby has the idea of an association already: a key and value paired together. It's used by Array#assoc
to look up a value from a list of pairs and by Hash#assoc
to return a key/value pair. Building up a mapping of key/value pairs is associating keys with values.
So! Consider Enumerable#associate
which builds a mapping by associating keys with values:
# Associate filenames with URLs. Before: