如何根据日期对Ruby Hash进行排序?

时间:2014-08-22 03:59:38

标签: ruby-on-rails ruby hash

我有一个具有以下结构的哈希对象:

{"action1"=>
  {"2014-08-20"=>0,
   "2014-07-26"=>1,
   "2014-07-31"=>1
  },
 "action2"=>
  {"2014-08-01"=>2,
   "2014-08-20"=>2,
   "2014-07-25"=>2,
   "2014-08-06"=>1,
   "2014-08-21"=>1
 }
 "action3"=>
  {"2014-07-30"=>2,
   "2014-07-31"=>1,
   "2014-07-22"=>1,
  }
}

我想根据日期对哈希进行排序并返回哈希(非数组)。最终结果应该是:

{"action1"=>
  {"2014-07-26"=>1,
   "2014-07-31"=>1,
   "2014-08-20"=>0
  },
 "action2"=>
  {"2014-07-25"=>2,
   "2014-08-01"=>2,
   "2014-08-06"=>2,
   "2014-08-20"=>1,
   "2014-08-21"=>1
 }
 "action3"=>
  {"2014-07-22"=>1,
   "2014-07-30"=>2,
   "2014-07-31"=>1
  }
}

3 个答案:

答案 0 :(得分:3)

迭代哈希值,并为每个值排序。

h = {"action1"=>
  {"2014-08-20"=>0,
   "2014-07-26"=>1,
   "2014-07-31"=>1
  },
 "action2"=>
  {"2014-08-01"=>2,
   "2014-08-20"=>2,
   "2014-07-25"=>2,
   "2014-08-06"=>1,
   "2014-08-21"=>1
 },
 "action3"=>
  {"2014-07-30"=>2,
   "2014-07-31"=>1,
   "2014-07-22"=>1,
  }
}

h.each do |k, v|
    h[k] = Hash[v.sort]
end

答案 1 :(得分:1)

这就是你所需要的:

h.each { |k,v| h[k] = v.sort.to_h }
  #=> {"action1"=>{"2014-07-26"=>1, "2014-07-31"=>1, "2014-08-20"=>0},
  #    "action2"=>{"2014-07-25"=>2, "2014-08-01"=>2, "2014-08-06"=>1,
  #       "2014-08-20"=>2, "2014-08-21"=>1},
  #    "action3"=>{"2014-07-22"=>1, "2014-07-30"=>2, "2014-07-31"=>1}}

Hash#to_h出现在Ruby 2.0中。对于早期版本,请使用类方法Hash::[]:即将v.sort.to_h替换为Hash[v.sort]

答案 2 :(得分:1)

在这里,您需要迭代哈希并获取值,而不是在每个值上应用 sort_by 函数,以便获得结果

hashName.each do |key, hash|
  Hash[hashName.sort_by{|k,v| k}]
end