ruby 数组 Hash相互转换

寻技术 Ruby编程 2023年07月11日 104
  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

关闭

用微信“扫一扫”