inicio mail me! sindicaci;ón

Archive for Oktober, 2010

Ruby: map Array to Hash

Sometimes you may wish to map an Array to a Hash in Ruby, like say, you got the output of I18n.available_locales

locales = [:en, :de, :fr]

and want to transform that into a Hash to fill a select element, like so:

{:en => 'EN', :de => 'DE', :fr => 'FR'}

How do you do that in the most concise way?
First, there is always inject:

locales.inject({}) {|hsh, sym| hsh[sym] = sym.to_s.upcase; hsh}

But I like the following approach way better, mainly because it emphasizes my intention more clearly (and, btw. is faster too):

Hash[locales.map{|sym| [sym, sym.to_s.upcase]}]

Remember: Hash[[[:a,:b],[:c,:d]]] (as well as Hash[:a,:b,:c,:d])
produces {:a => :b, :c => :d}.