代码之家  ›  专栏  ›  技术社区  ›  Pascal

如何使用数组封送哈希?

  •  1
  • Pascal  · 技术社区  · 15 年前

    我该怎么办 封送数组的哈希? 以下代码仅打印 {} .

    s = Hash.new
    s.default = Array.new
    s[0] << "Tigger"
    s[7] << "Ruth"
    s[7] << "Puuh"
    data = Marshal.dump(s)
    ls = Marshal.restore( data )
    p ls
    

    如果哈希不包含数组,则会正确还原。

    4 回复  |  直到 15 年前
        1
  •  7
  •   steenslag    15 年前
    s = Hash.new
    s.default = Array.new
    s[0] << "Tigger"
    s[7] << "Ruth"
    s[7] << "Puuh"
    

    此代码更改默认值3次(这可能是转储中显示的内容),但它不会在哈希中存储任何内容。试试“Puts S[8]”,它会返回[“Tigger”]、[“Ruth”]、[“Puuh”]。

    hash.default_proc将执行您想要的操作

    s = Hash.new{|hash,key| hash[key]=[] }
    

    但你不能整理程序。这将起作用:

    s = Hash.new
    s.default = Array.new
    s[0] += ["Tigger"]
    s[7] += ["Ruth"]
    s[7] += ["Puuh"]
    

    这是因为[]+=[“Tigger”]创建了一个 新的 数组。 另一种方法是创建较少的阵列:

    s = Hash.new
    (s[0] ||= []) << "Tigger"
    (s[7] ||= []) << "Ruth"
    (s[7] ||= []) << "Puuh"
    

    仅在缺少键(nil)时创建新数组。

        2
  •  2
  •   fl00r    15 年前

    您可以在初始化hash.new时创建散列结构以避免此类问题

    h = Hash.new{ |a,b| a[b] = [] }
    h[:my_key] << "my value"
    
        3
  •  1
  •   Jonathan Julian    15 年前

    你可能会被误导 Hash.default 作品.

    在你之前 Marshal.dump ,打印数据结构。它是 {} . 这是因为您要将每个字符串连接成nil,而不是空数组。下面的代码说明并解决了您的问题。

    s = Hash.new
    s.default = Array.new
    s[0] = []
    s[0] << "Tigger"
    s[7] = []
    s[7] << "Ruth"
    s[7] << "Puuh"
    p s
    data = Marshal.dump(s)
    ls = Marshal.restore( data )
    p ls
    

    返回:

    {0=>["Tigger"], 7=>["Ruth", "Puuh"]}
    {0=>["Tigger"], 7=>["Ruth", "Puuh"]}
    

    编辑:

    我在哈希表中插入了大量数据

    因此,也许一些帮助程序代码可以使插入过程更平滑:

    def append_to_hash(hash, position, obj)
      hash[position] = [] unless hash[position]
      hash[position] << obj
    end
    
    s = Hash.new
    append_to_hash(s, 0, "Tigger")
    append_to_hash(s, 7, "Ruth")
    append_to_hash(s, 7, "Puuh")
    s.default = Array.new // this is only for reading
    p s
    data = Marshal.dump(s)
    ls = Marshal.restore( data )
    p ls
    
        4
  •  0
  •   Arkku    15 年前

    因为你不能用 Marshall.dump 对于具有默认元素proc的哈希,可以使用稍微更为迂回的方法来附加到每个数组,而不是 << :

    s = Hash.new
    s.default = []
    s[0] += [ "Tigger" ]
    s[7] += [ "Ruth" ]
    s[7] += [ "Pooh" ]
    data = Marshal.dump(s)
    ls = Marshal.restore(data)
    p ls