我有一个这样的数组:
["Is", "Gandalf", "The", "Gray", "Insane"]
我想根据数组中键的位置对哈希进行排序。例如,我想排序:
{:count=>21, "Is"=>19, "Gandalf"=>1, "Gray"=>0, "Insane"=>1, "The"=>5}
进入这个:
{"Is"=>19, "Gandalf"=>1, "The"=>5, "Gray"=>0, "Insane"=>1, :count=>21}
另一个例子是对此进行排序:
{:count=>3, "Is"=>11, "Insane"=>22, "Gray"=>0, "Gandalf"=>12, "The"=>2}
进入这个:
{"Is"=>11, "Gandalf"=>12, "The"=>2, "Gray"=>12, "Insane"=>22, :count=>3}
如何做到这一点?
答案 0 :(得分:3)
class Hash
def sort_by_array a; Hash[sort_by{|k, _| a.index(k) || length}] end
end
将适用于第一个示例:
a = ["Is", "Gandalf", "The", "Gray", "Insane"]
{:count=>21, "Is"=>19, "Gandalf"=>1, "Gray"=>0, "Insane"=>1, "The"=>5}.sort_by_array(a)
# => {"Is"=>19, "Gandalf"=>1, "The"=>5, "Gray"=>0, "Insane"=>1, :count=>21}
但是,它不适用于您的第二个示例,因为您期望第二个示例的结果不仅仅是排序,还需要更改"Gray"
的值:
{:count=>3, "Is"=>11, "Insane"=>22, "Gray"=>0, "Gandalf"=>12, "The"=>2}.sort_by_array(a)
# => {"Is"=>11, "Gandalf"=>12, "The"=>2, "Gray"=>0, "Insane"=>22, :count=>3}
# You wanted
# => {"Is"=>11, "Gandalf"=>12, "The"=>2, "Gray"=>12, "Insane"=>22, :count=>3}
由于不清楚12
的值"Gray"
来自何处,因此无法以满足第二个示例的方式回答您的问题。
答案 1 :(得分:0)
我建议,通过按照您需要的顺序填充数组,将其转换为数组。 然后,您可以使用该数组访问数组本身,或者将该数组转换为hashmap。
http://x3ro.de/ruby-19-array-hash/
讨论类似行的一个链接是,