数组生成哈希表的方法示例

以下是从数组生成哈希表的方法示例

  1. 由[索引, 值, ...] 型的数组变为哈希表

    ary = [1,"a", 2,"b", 3,"c"]
    p Hash[*ary]
    
    # => {1=>"a", 2=>"b", 3=>"c"}
    
  2. 由索引和值配对出现的数组变为哈希表

    alist = [[1,"a"], [2,"b"], [3,"c"]]
    p Hash[*alist.flatten]
    
    #=> {1=>"a", 2=>"b", 3=>"c"}
    
  3. 由索引数组和值数组配对生成哈希表(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"}
    
  4. 虽然索引和值都是数组,但还是无法使用(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"]}

你可能感兴趣的:(数组生成哈希表的方法示例)