-1

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

{
  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
  }
}
4

2 回答 2

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
于 2013-07-04T15:08:07.123 回答
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
于 2013-07-04T18:14:13.680 回答