ruby 数组 Hash相互转换

  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"]}

参考链接:http://www.kuqin.com/rubycndocument/man/built-in-class/class_object_hash.html

posted @ 2013-07-29 10:00  dami.van  阅读(1492)  评论(0编辑  收藏  举报