I use the following snippet a lot, and think it's worth including in
the Ruby built-in Array class.
class Array
def to_h(default = nil)
result = Hash.new(default)
each_with_index do |value, index|
result[index] = value
end
result
end
end
Example usage:
[:a, :b, :c].to_h # => {0=>:a, 1=>:b, 2=>:c}
I often use it in processing comma-separated variable (CSV) files with
a header row, for example:
header_row = "year,month,day,price\n"
index_of = header_row.chomp.split(',').to_h.invert
# => {"month"=>1, "price"=>3, "day"=>2, "year"=>0}
data_row = "2002,1,17,1.5\n"
cells = data_row.chomp.split(',')