由[索引, 值, ...] 型的数组变为哈希表
ary = [1,"a", 2,"b", 3,"c"]
p Hash[*ary] # => {1=>"a", 2=>"b", 3=>"c"}由索引和值配对出现的数组变为哈希表
alist = [[1,"a"], [2,"b"], [3,"c"]]
p Hash[*alist.flatten] #=> {1=>"a", 2=>"b", 3=>"c"}由索引数组和值数组配对生成哈希表(version 1.7 以后)
keys = [1, 2, 3]
vals = ["a", "b", "c"]
alist = keys.zip(vals) # 或 alist = [keys,vals].transpose
p Hash[*alist.flatten] #=> {1=>"a", 2=>"b", 3=>"c"}虽然索引和值都是数组,但还是无法使用(2)或(3)的方法时,只好老老实实地赋值了
h = Hash.new
alist = [[1,["a"]], [2,["b"]], [3,["c"]]]
alist.each {|k,v|
h[k] = v
}
p h #=> {1=>["a"], 2=>["b"], 3=>["c"]}
参考链接:http://www.kuqin.com/rubycndocument/man/built-in-class/class_object_hash.html