在散列哈希中检索最大值的键

时间:2013-07-04 14:49:15

标签: ruby

我有一个返回像这样的哈希设置的方法

{
  user_id => { date => count, date => count },
  user_id => { date => count, date => count }
}

我如何以最高排名来订购此列表?

编辑:抱歉,我没有具体,我有一个日期和值的哈希值。我想获得最近一个月的最高排名。

my_hash = {
  3 => {
    "2013-07-01 00:00:00+00" => 1
  },
  6 => {
    "2013-06-01 00:00:00+00" => 1,
    "2013-07-01 00:00:00+00" => 2
  },
  5 => {
    "2013-06-01 00:00:00+00" => 2,
    "2013-07-01 00:00:00+00" => 5
  }
}

2 个答案:

答案 0 :(得分:4)

这样的事情应该有效:

hash = {
  1 => { 'a' => 2, 'b' => 4 },
  2 => { 'c' => 6, 'd' => 12 },
  3 => { 'e' => 8, 'f' => 10 }
}

Hash[hash.sort_by { |user_id, date_counts| date_counts.values.max }.reverse!]
#=> {2=>{"c"=>6, "d"=>12}, 3=>{"e"=>8, "f"=>10}, 1=>{"a"=>2, "b"=>4}}

<强>更新

这会提取date - count对,并将它们从最高到最低排序:

sorted = my_hash.values.flat_map(&:to_a).sort.reverse
#=> [["2013-07-01 00:00:00+00", 5], ["2013-07-01 00:00:00+00", 2], ["2013-07-01 00:00:00+00", 1], ["2013-06-01 00:00:00+00", 2], ["2013-06-01 00:00:00+00", 1]]

第一个是具有最高计数的最近日期:

sorted.first[1] # => 5

答案 1 :(得分:2)

我认为Enumerable#max_by对于同一个人来说是个不错的选择:

my_hash = {
  3 => {
    "2013-07-01 00:00:00+00" => 1
  },
  6 => {
    "2013-06-01 00:00:00+00" => 1,
    "2013-07-01 00:00:00+00" => 2
  },
  5 => {
    "2013-06-01 00:00:00+00" => 2,
    "2013-07-01 00:00:00+00" => 5
  }
}

my_hash.max_by{|k,v| v.max_by{|k1,v1| [k1,v1]}}
# => [5, {"2013-06-01 00:00:00+00"=>2, "2013-07-01 00:00:00+00"=>5}]
#if you want user  id of highest count for the the most recent month.
my_hash.max_by{|k,v| v.max_by{|k1,v1| [k1,v1]}}.first
# => 5
# highest count for the the most recent month.
my_hash.max_by{|k,v| v.max_by{|k1,v1| [k1,v1]}}[-1].values[-1]
# => 5
相关问题