给定一个包含有关订单条件信息的数组的散列

时间:2012-03-07 22:57:08

标签: ruby-on-rails ruby hash

我正在使用Ruby on Rails 3.1,我希望通过关注另一个Hash中的“声明”/“指定”顺序来订购Array Array# 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", ] } 。也就是说,例如,我有:

# This is the Array mentioned above.

array = [m, 3, 1, 2]

hash

我想在array中将# 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", ] } 个密钥命名为“陈述”/“已指定”,以便

Enumerable

我该怎么做(可能使用{{1}} Ruby模块或者我不熟悉的Ruby on Rails方法)

2 个答案:

答案 0 :(得分:3)

sorted_array = hash.sort_by { |k,v| array.index(k) }

如果你想要订购和哈希,你需要使用ActiveSupport :: OrderedHash,例如。

sorted_array = hash.sort_by { |k,v| array.index(k) }
sorted_hash  = ActiveSupport::OrderedHash[sorted_array]

答案 1 :(得分:0)

在这个玩具示例中,James使用array.index的方法会很好,但是如果哈希或数组很大,你就不想一遍又一遍.index。更有效的方式是:

Hash[*array.map {|i| [i, hash[i]]}]