0

我想存储与键关联的三元组数据。我有这种形式的三元组:

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

我该怎么做这个红宝石?

4

1 回答 1

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"]]}
于 2013-09-27T10:59:08.423 回答