如何在ruby on rails上将给定的哈希解析为所需的输出?

时间:2017-06-13 11:25:19

标签: ruby-on-rails ruby ruby-on-rails-4 ruby-hash

我必须向用户发送每日课程更新通知。更新通知包含四种类型的[: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"
      }
    }
  }
}

1 个答案:

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