Ruby: Converting an Array to a Hash
By chris on October 7th 2007 in /dev/ruby | 503 views
Converting a hash into an array in Ruby is easy but what about an array into a hash? This code does the trick quite nicely, and if you don't want to actually extend the Array class this does as well:
RUBY:
-
a = ["cat","dog","monkey"]
-
h = Hash[*a.collect { |v| [a.index(v), v] }.flatten]
Update: Speaking of mucking about with arrays, ArraySugar adds a few nice shortcuts to arrays. I like the select syntax (but it seems like overkill to install this as a gem).
