按二级数组中的键顺序排序哈希

时间:2014-09-08 00:47:44

标签: ruby arrays sorting select hash

我有一个哈希:

hash = {"a" => 1, "b" =>2, "c" => 3, "d" => 4}

我有一个阵列:

array = ["b", "a", "d"]

我想创建一个新的数组,该数组由原始哈希值组成,原始哈希值也可以在原始数组中找到,同时保持原始数组的顺序。所需的数组是:

desired_array = [2, 1, 3]

这里的想法是取“坏”这个词,为字母分配数字,然后按顺序制作一个与“b”“a”和“d”对应的数字数组。

4 个答案:

答案 0 :(得分:1)

因为你的问题有点不清楚我假设你想让desired_array成为一个数组(你说你想要一个新的数组并用新的哈希完成句子)。同样在你的例子中,我假设你希望desired_array为['b','a','d']为[2,1,4]而对于['b','不是[2,1,3] a','c']。

您应该使用Enumerable#map方法创建一个数组,将第一个数组映射到您想要的数组,如下所示:

desired_array = array.map { |k| hash[k] }

你应该熟悉Enumerable#map方法,这是一个非常方便的方法。从方法的rubydocs:为枚举中的每个元素返回一个新数组,其中包含一次运行块的结果。所以在这种情况下,我们迭代数组并调用hash [k]从散列中选择值并创建一个新的数组,其中包含由散列选择的值。由于迭代是有序的,因此您将保持原始序列。

答案 1 :(得分:0)

我会使用Enumerable#map后跟Enumerable#sort_byfor example

hash = {"d" => 4, "b" =>2, "c" => 3, "a" => 1}
order = ["b", "a", "d"]

# For each key in order, create a [key, value] pair from the hash.
# (Doing it this way instead of filtering the hash.to_a is O(n) vs O(n^2) without
#  an additional hash-probe mapping. It also feels more natural.)
selected_pairs = order.map {|v| [v, hash[v]]}
# For each pair create a surrogate ordering based on the `order`-index
# (The surrogate value is only computed once, not each sort-compare step.
#  This is, however, an O(n^2) operation on-top of the sort.)
sorted = selected_pairs.sort_by {|p| order.find_index(p[0]) }

p sorted

# sorted =>
# [["b", 2], ["a", 1], ["d", 4]]

将结果变回哈希,因为我相信哈希应该被视为有任何秩序,除了调试辅助工具。 (请记住,Ruby 2哈希值是按插入顺序排列的。)

答案 2 :(得分:0)

您需要的只是values_at

hash.values_at *array

答案 3 :(得分:0)

可数方法映射,每个方法都很完美
desired_array = array.map {| k |哈希[k]} 要么 desired_array = array.each {| k |哈希[k]}

相关问题