I am using Ruby on Rails 3.0.7 and I would like to sort an hash
considering a preset order by returning a sorted array
or even a new sorted hash
. That is, given the following hash
, say HASH1 (for which I consider its values to indicate the order method from 1 to 4)
{
:dog => 3,
:cat => 2,
:pig => 4,
:frog => 1
}
I would like to sort this other hash
by key, s开发者_开发知识库ay HASH2, by considering the order given in HASH1 values
{
:cat => 'cat_value',
:dog => 'dog_value',
:frog => 'frog_value',
:pig => 'pig_value'
}
So, in the above case, I should have the outputted\ordered hash
like the following:
{
: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
}
or
[
["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
]
How can I do that?
Use 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]
Output
[[:frog, [1]], [:cat, [2]], [:dog, [3]], [:pig, [4]]]
{:frog=>[1], :cat=>[2], :dog=>[3], :pig=>[4]}
精彩评论