我有一堆带有类别标签的文章。
我想知道每个类别已经被使用了多少次。
我正在使用Rails和MongoDB,但我认为我不需要从数据库中获取类别出现的次数,所以Mongo部分应该无关紧要。
这是我目前的代码:
@recent_posts = current_user.recent_posts #返回最近的10篇文章 @categories_hash = {'tech' => 0, 'world' => 0, 'entertainment' => 0, 'sports' => 0} @recent_posts.each do |post| post.categories.each do |category| @categories_hash[category] += 1 #显然,这是我遇到问题的地方 end end
文章的结构如下:
{"_id" : ObjectId("idnumber"), "created_at" : "Tue Aug 03...", "categories" :["world", "sports"], "message" : "the text of the post", "poster_id" : ObjectId("idOfUserPoster"), "voters" : []}
我欢迎任何其他获取类别计数的建议,但我最终会想要获取投票人数,所以对我来说似乎最好的方法是增加categories_hash的值,然后再添加voters.length,但是一步一步来,我只是试图弄清楚如何递增哈希中的值。
我正在使用Rails和MongoDB,但我认为我不需要从数据库中获取类别出现的次数,所以Mongo部分应该无关紧要。
这是我目前的代码:
@recent_posts = current_user.recent_posts #返回最近的10篇文章 @categories_hash = {'tech' => 0, 'world' => 0, 'entertainment' => 0, 'sports' => 0} @recent_posts.each do |post| post.categories.each do |category| @categories_hash[category] += 1 #显然,这是我遇到问题的地方 end end
文章的结构如下:
{"_id" : ObjectId("idnumber"), "created_at" : "Tue Aug 03...", "categories" :["world", "sports"], "message" : "the text of the post", "poster_id" : ObjectId("idOfUserPoster"), "voters" : []}
我欢迎任何其他获取类别计数的建议,但我最终会想要获取投票人数,所以对我来说似乎最好的方法是增加categories_hash的值,然后再添加voters.length,但是一步一步来,我只是试图弄清楚如何递增哈希中的值。
@categories_hash = Hash.new(0)
,或者像原问题中那样初始化它,就可以删除@categories_hash[category] ||= 0
这一行。 - Sophie Alpert