0

我必须向用户发送每日课程更新通知。更新通知包含四种类型[:due,:missed,:over_due,:new]。为了方便起见,我从数据中省略了不必要的字段,例如到期和错过,因为它与过期和新格式相同。下面提供的数据属于用户。用户可以是许多课程的一部分,这就是为什么哈希中有 2 个不同的 course_id(course_id 20 和 30)。id 在这里代表特定课程中的 assignment_id。数据的实际格式是。

  { 
   1 => { #the 1st user
     :new => {
          1 => {
           :id => 1,
           :course_id =>20,
           :course_name => "B"
          },
          2 => {
           :id => 2,
           :course_id =>30,
           :course_name => "A"
         },
         3 => {
           :id => 3,
           :course_id =>20,
           :course_name => "B"
         }
       }
       :over_due => {}, #This is also having the same format as new
       :missed => {}, #This is also having the same format as new
       :due => {} #This is also having the same format as new
     },
    2 => { #this is 2nd user
       :new => {},
       :over_due => {},
       :missed => {},
       :due => {}
     }
   }

假设,这只是我为用户创建的虚拟数据,以便更清楚和解释。

assignments = {
  :new => {
    1 => {
      :id => 1,
      :course_id => 20,
      :name => "A"
    },
    2 => {
      :id => 2,
      :course_id => 20,
      :name=>"A"
    },
    3 => {
      :id => 3,
      :course_id => 30,
      :name=>"B"
    }
  },
  :over_due => {
    4 => {
      :id => 4,
      :course_id => 20,
      :name => "A"
    },
    5 => {
      :id => 5,
      :course_id => 30,
      :name => "B"
    }
  }
}

我将数据解析为这种格式的要求:

{
  20 => {
    :new => {
      1 => {
        :id => 1,
        :course_id => 20,
        :name=>"A"
      },
      2 => {
        :id => 2,
        :course_id => 20,
        :name => "B"
      }
    },
    :over_due => {
      4 => {
        :id => 4,
        :course_id => 20,
        :name => "E"
      }
    }
  },
  30 => {
    :new => {
      3 => {
        :id => 3,
        :course_id => 30,
        :name => "C"
      }
    },
    :over_due => {
      5 => {
        :id => 5,
        :course_id => 30,
        :name=>"F"
      }
    }
  }
}
4

1 回答 1

1

检查以下代码以获取您的解决方案:

 hash = {} 
 assignments.each do |type,type_data| 
    type_data.each do |assignment_id,data| 
        course_id = data[:course_id]
        hash[course_id] = {} if hash[course_id].nil?
        hash[course_id][type]= {} if hash[course_id][type].nil?
        hash[course_id][type][assignment_id] = data 
    end 
end

输出:

{20=>{:new=>{1=>{:id=>1, :course_id=>20, :name=>"A"}, 2=>{:id=>2, :course_id=>20, :name=>"B"}}, :over_due=>{4=>{:id=>4, :course_id=>20, :name=>"E"}}}, 30=>{:new=>{3=>{:id=>3, :course_id=>30, :name=>"C"}}, :over_due=>{5=>{:id=>5, :course_id=>30, :name=>"F"}}}}
于 2017-06-13T12:18:33.900 回答