class Array def invert h={} self.each_with_index{|x,i| h[x]=i} h end end a = ["red","yellow","orange"] h = a.invert # {"orange"=>2, "yellow"=>1, "red"=>0}