3

我有一个这样的数组:

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

如何做到这一点?

4

2 回答 2

4
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}

由于尚不清楚12for的值"Gray"来自何处,因此无法以满足您的第二个示例的方式回答您的问题。

于 2013-01-03T14:45:19.027 回答
0

我建议,通过按您需要的顺序填充数组,将其转换为数组。然后,您可以通过使用该数组或将该数组转换为哈希图来访问该数组本身。

http://x3ro.de/ruby-19-array-hash/

讨论类似行的一个链接是,

如何排序不简单的散列(散列的散列)

于 2013-01-03T14:10:41.443 回答