给出另一个散列的散列,包括有关order方法的信息

时间:2011-06-28 22:32:28

标签: ruby-on-rails ruby arrays sorting hash

我正在使用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
]

我该怎么做?

1 个答案:

答案 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]}