每个循环内按月分组

时间:2012-11-15 05:28:53

标签: ruby-on-rails ruby ruby-on-rails-3

在我的以下代码中,我必须按月分组风险。任何人都可以帮助我如何按月分组

          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

由于

2 个答案:

答案 0 :(得分: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

答案 1 :(得分: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
          }
}