I often find myself building lookup tables in Ruby, generally to cache some expensive computation or to build something I'm passing to a view. I figure there must be a short, readable idiom for this, but we couldn't think of one. For example, suppose I want to start with
[65, 66, 67, ...]
and end up with
{65 => "A", 66 => "B", 67 => "C", ...}
The not-quite-pretty-enough idioms we could think of include:
array = (65..90).to_a
array.inject({}) {|hash, key| hash[key]=key.chr; hash}
{}.tap {|hash| array.each {|key| hash[key] = key.chr}}
Hash[array.zip(array.map{|key| key.chr})]
But all of these are a little painful: hard to read, easy to mess up, not clear in intent. Surely Ruby (or some Rails helper) has some nice magic for this?