我必须向用户发送每日课程更新通知。更新通知包含四种类型的[:due,:missed,:over_due,:new]
。为了方便起见,我省略了不必要的数据字段,如过期和新格式一样。以下提供的数据属于用户。用户可以成为许多课程的一部分,这就是为什么2个不同的course_id存在于散列(course_id 20和30)中的原因。 id代表特定课程中的assignment_id。 数据的实际格式是。如何将给定的散列解析为轨道上的ruby所需的输出?
{
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"
}
}
}
}
首先,告诉我们什么你到目前为止尝试过。那么,清晰*单词*的预期结果是什么。你的一些哈希已经将':course_id'转换为''value'',其他一些没有...给我们一些见解。 –
我已经更新了这个问题。看下面的代码。 hash = {} assignments.each do | type,type_data | type_data.each do | assignment_id,data | COURSE_ID =数据[:COURSE_ID] 散列[COURSE_ID] = {} 散列[COURSE_ID] [类型] = {} 散列[COURSE_ID] [类型] [assignment_id] =数据 端 端 –
@MukeshKumarGupta不要在评论部分编写代码,阅读起来非常困难。请[编辑你的帖子](https://stackoverflow.com/posts/44520178/edit)并很好地格式化。 –