如果您正在使用 Rails 或已包含active_support
,那么您可以group_by
像这样使用:
analysis_response.histories.group_by(&:month)
根据月份的类型,您将获得如下所示的哈希:
{
:jan => [<history>, <history>],
:feb => [<history>],
...
:dec => [<history>, <history>]
}
要按风险分组,请执行以下操作:
risk_levels = [:low, :medium, :high]
analysis_response.histories.compact.group_by do |month, history|
risk_levels[get_risk(history.probability, history.consequence)]
end
产生这样的哈希:
{
:low => [<history>, <history>],
:medium => [<history>, <history>],
:high => [<history>, <history>]
}
如果您尝试按月对风险级别进行分组,请执行以下操作:
grouped_histories = {}
risk_levels = [:low, :medium, :high]
analysis_response.histories.group_by(&:month).each_pair do |month, histories|
risk_histories = histories.compact.group_by do |history|
risk_levels[get_risk(history.probability, history.consequence)]
end
risk_histories.each_pair do |risk, history_list|
grouped_histories[:month][risk] = history_list.size
end
end
给你这个:
{
:jan => {
:low => 1,
:medium => 2
:high => 0
},
:feb => {
:low => ...you get the idea
}
}