我想存储与密钥相关的三元组数据。我有这种形式的三元组:
"data1" "data2" "data3"
其中data1
是一个整数。我有一个三倍于密钥的机制。例如,"key1"
映射到
["data1", "data2", "data3"]
可以有多个与密钥相关联的三元组。例如,[4, "data2", "data3"], [1, "data5", "data6"] and [3, "data8", "data9"]
可能会映射到"key1"
。我希望这些三元组按"data1"
字段排序并映射。在这种情况下,
"key1" => {[1, "data5", "data6"] [3, "data8", "data9"] [4, "data2", "data3"]}
我如何做这个Ruby?
答案 0 :(得分:0)
您可以执行以下操作:
hsh = {"key1" => [[4,"data2","data3"], [1, "data5","data6"],[3, "data8","data9"]] }
hsh.each{|k,v| hsh[k]=v.sort_by(&:first)}
p hsh
# >> {"key1"=>[[1, "data5", "data6"], [3, "data8", "data9"], [4, "data2", "data3"]]}
如果您不想更新源哈希,请使用#dup
。
hsh = {"key1" => [[4,"data2","data3"], [1, "data5","data6"],[3, "data8","data9"]] }
hsh1 = hsh.dup
hsh1.each{|k,v| hsh1[k]=v.sort_by(&:first)}
p hsh1
# >> {"key1"=>[[1, "data5", "data6"], [3, "data8", "data9"], [4, "data2", "data3"]]}