-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 を使用しているか、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 に答える