英文:
How to sort hash keys based on array keys?
问题
这是一个哈希的示例:
h1 = {
a1: :a2,
b1: :b2,
c1: :c2,
d1: :d2,
e1: :e2,
f1: :f2
}
还有这样一个键的数组:
a1 = [:b1, :d1, :f1]
如何根据数组对此哈希的键进行排序?不在数组中的哈希键必须按它们原来的顺序排列在已排序的键后面。
结果:
{
b1: :b2,
d1: :d2,
f1: :f2,
a1: :a2,
c1: :c2,
e1: :e2
}
英文:
There is an example of a hash:
h1 = {
a1: :a2,
b1: :b2,
c1: :c2,
d1: :d2,
e1: :e2,
f1: :f2
}
And there is such an array of keys:
a1 = [:b1, :d1, :f1]
How to sort the keys of this hash based on the array? The hash keys that are not in the array must come after the sorted ones in the order in which they were.
Result:
{
b1: :b2,
d1: :d2,
f1: :f2,
a1: :a2,
c1: :c2,
e1: :e2
}
答案1
得分: 7
Hash#slice
方法按照 a1
中定义的顺序返回 h1
中的元素。而 Hash#except
方法返回不在 a1
中的元素。最后,Hash#merge
方法将这两组元素合并成一个哈希表。
英文:
I would do this:
h1.slice(*a1).merge(h1.except(*a1))
#=> {:b1=>:b2, :d1=>:d2, :f1=>:f2, :a1=>:a2, :c1=>:c2, :e1=>:e2}
Hash#slice
returns the elements from h1
in the order how they are defined in a1
. And the Hash#except
returns the missing ones. And Hash#merge
merges both groups into one hash.
答案2
得分: 4
You may write
h1.slice(*a1, *(h1.keys - a1))
or
h1.slice(*a1, *h1.keys)
Both return
{:b1=>:b2, :d1=>:d2, :f1=>:f2, :a1=>:a2, :c1=>:c2, :e1=>:e2}
See Hash#slice.
英文:
You may write
h1.slice(*a1, *(h1.keys - a1))
or
h1.slice(*a1, *h1.keys)
Both return
{:b1=>:b2, :d1=>:d2, :f1=>:f2, :a1=>:a2, :c1=>:c2, :e1=>:e2}
See Hash#slice.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论