我正在使用Ruby on Rails 3.0.7,我想通过返回已排序的hash
甚至是新的已排序array
来考虑预设顺序对hash
进行排序。也就是说,给定以下hash
,比如说HASH1(我认为它的值表示从1到4的顺序方法)
{
:dog => 3,
:cat => 2,
:pig => 4,
:frog => 1
}
我想通过考虑HASH1值中给出的顺序,按键(HASH2)对另一个hash
进行排序
{
:cat => 'cat_value',
:dog => 'dog_value',
:frog => 'frog_value',
:pig => 'pig_value'
}
所以,在上面的例子中,我应该输出\ ordered {ordered hash
,如下所示:
{
:frog => 'frog_value', # Order indicated by ':frog => 1' in the HASH1
:cat => 'cat_value', # Order indicated by ':cat => 2' in the HASH1
:dog => 'dog_value', # Order indicated by ':dog => 3' in the HASH1
:pig => 'pig_value' # Order indicated by ':pig => 4' in the HASH1
}
或
[
["frog", 'frog_value'], # Order indicated by ':frog => 1' in the HASH1
["cat", 'cat_value'], # Order indicated by ':cat => 2' in the HASH1
["dog", 'dog_value'], # Order indicated by ':dog => 3' in the HASH1
["pig", 'pig_value'] # Order indicated by ':pig => 4' in the HASH1
]
我该怎么做?
答案 0 :(得分:2)
使用Hash#sort_by
:
hash = {
:cat => [2],
:frog => [1],
:pig => [4],
:dog => [3]
}
order = {
:dog => 3,
:cat => 2,
:pig => 4,
:frog => 1
}
# array of k, v pairs
p sorted_array = hash.sort_by {|k, v| order[k]}
p sorted_hash = Hash[sorted_array]
输出
[[:frog, [1]], [:cat, [2]], [:dog, [3]], [:pig, [4]]]
{:frog=>[1], :cat=>[2], :dog=>[3], :pig=>[4]}