我有一个通知页面。与社交网站上的任何通用通知页面一样。每个通知都有一个unix时间戳。我想根据天数将通知分成多维哈希。哈希键可以表示它的日期。例如:
notification['3July'][0] = 'Answered a question'
notification['3July'][1] = 'Answer got 13 upvotes'
notification['3July'][2] = 'Earned a badge'
....
notification['23June'][0] = 'Set a bounty of 50 credits'
notification['23June'][1] = 'Followed XYZ'
notification['23June'][2] = 'Added a question on stack overflow'
然后我会遍历多维哈希并在每天下发布通知。目前我从数据库中获取数据,格式如下:
notification[0] = { 'text' => 'Answered a question' , 'timestamp' => 123456 }
notification[1] = { 'text' => 'Answer got 13 upvotes' , 'timestamp' => 123456 }
notification[2] = { 'text' => 'Earned a badge' , 'timestamp' => 123456 }
....
notification[3] = { 'text' =>'Set a bounty of 50 credits' , 'timestamp' => 123456 }
notification[4] = { 'text' =>'Followed XYZ' , 'timestamp' => 123456 }
notification[5] = { 'text' =>'Added a question on stack overflow' , 'timestamp' => 123456 }
在Ruby / Rails中执行此操作的最干净,最优化的方法是什么?
答案 0 :(得分:1)
按时间戳订购通知,添加一列以选择仅具有日期的内容,然后在Ruby中使用group_by
。这应该是获得它的最简单方法。
要选择其他列,您应该为其添加attr_accessor
。
http://www.ruby-doc.org/core-2.0/Enumerable.html#method-i-group_by