我有一个这样的数组:
["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}
如何做到这一点?
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}
由于不清楚 "Gray"
的值 12
从何而来,因此无法以满足第二个示例的方式回答您的问题。