I am using Ruby on Rails 3.1 and I would like to order a Hash of Arrays by caring the order “stated”/”specified” in another Array. That is, for example, I have:
# This is the Hash of Arrays mentioned above.
hash = {
1 => [
"Value 1 1",
"Value 1 2",
"Value 1 n",
],
2 => [
"Value 2 1",
"Value 2 2",
"Value 2 n",
],
3 => [
"Value 3 1",
"Value 3 2",
"Value 3 n",
],
m => [
"Value m 1",
"Value m 2",
"Value m n",
]
}
and
# This is the Array mentioned above.
array = [m, 3, 1, 2]
I would like to order hash keys as “stated”/”specified” in the array in order to have:
# Note that Hash keys are ordered as in the Array.
ordered_hash = {
m => [
"Value m 1",
"Value m 2",
"Value m n",
],
3 => [
"Value 3 1",
"Value 3 2",
"Value 3 n",
],
1 => [
"Value 1 1",
"Value 1 2",
"Value 1 n",
],
2 => [
"Value 2 1",
"Value 2 2",
"Value 2 n",
]
}
How can I make that (maybe using the Enumerable Ruby module or some unknown to me Ruby on Rails method)?
If you want ordering and a Hash, you’ll need to use ActiveSupport::OrderedHash, e.g.