-1

在我的以下代码中,我必须按月对风险进行分组。谁能帮我按月分组

          analysis_response.histories.each do |month, history|
            @low = 0
            @medium = 0
            @high = 0
            if history != nil
              risk = get_risk(history.probability, history.consequence)
              if risk === 0
                @low += 1
              elsif risk === 1
                @medium += 1
              elsif risk === 2
                @high += 1
              end
            end
          end

谢谢

4

2 回答 2

1

为什么不试试这个?(简单的一种)

month_risk = {}
analysis_response.histories.each do |month, history|
  @low = 0
  @medium = 0
  @high = 0
  if history != nil
    risk = get_risk(history.probability, history.consequence)
    if risk === 0
      @low += 1
    elsif risk === 1
      @medium += 1
    elsif risk === 2
      @high += 1
    end
  end
  month_risk[month] = {low: @low, medium: @medium, high: @high}
end

# You can get them via month_risk[month][:low] etc, where month is sym or str as you like
于 2012-11-15T06:08:05.500 回答
0

如果您正在使用 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
          }
}
于 2012-11-15T05:57:13.777 回答